如何在react-router-v4中通过代码跳转子路由?

#1

我想完成一个功能就是在搜索框完成输入后,敲击回车跳转到另外一个组件,现在我监听了键盘事件,请问怎么才能用代码路由到某个组件A,假设A已经在Route中配置好了路径。

#2

history 对象通常会具有以下属性和方法:

length -( number 类型)指的是 history 堆栈的数量。
action -( string 类型)指的是当前的动作(action),例如 PUSH,REPLACE 以及 POP 。
location -( object类型)是指当前的位置(location),location 会具有如下属性:
pathname -( string 类型)URL路径。
search -( string 类型)URL中的查询字符串(query string)。
hash -( string 类型)URL的 hash 分段。
state -( string 类型)是指 location 中的状态,例如在 push(path, state) 时,state会描述什么时候 location 被放置到堆栈中等信息。这个 state 只会出现在 browser history 和 memory history 的环境里。
push(path, [state]) -( function 类型)在 hisotry 堆栈顶加入一个新的条目。
replace(path, [state]) -( function 类型)替换在 history 堆栈中的当前条目。
go(n) -( function 类型)将 history 对战中的指针向前移动 n 。
goBack() -( function 类型)等同于 go(-1) 。
goForward() -( function 类型)等同于 go(1) 。
block(prompt) -( function 类型)阻止跳转

#3

怎么获得这个history 是在this上吗?问题是我这个组件里面没有路由,路由在它的父组件的父组件里面,我怎么获得这个history

#4

props传递history
类似这种:

history={this.props.history}
1 Like
#5

可以用withRouter ,然后this.props.history去操作。用法:

import {withRouter} from 'react-router'

 withRouter(MyComponent)


1 Like
#6

我把二位的回答综合了一下,解决了这个问题,非常感谢二位的耐心回答!

#7

把解决方案分享看看,让我学习学习。:laughing:

#8

就是一般的react组件它里面没有你说的那些match location history 只有Route包装的组件才有

  • 采用下面那个哥们的说法,包装react组件,让它获得history属性

@wlt 可以用withRouter ,然后this.props.history去操作。用法:
import {withRouter} from ‘react-router’
withRouter(MyComponent)

  • 就用你说的方法,在自己定义的组件的方法中,this.props.history.push(),或者this.props.history.replace()这样就代码跳转组件了
2 Likes