以编程方式导航到其他路线

时间:2017-09-07 03:32:01

标签: reactjs react-router react-redux react-router-v4 react-router-redux

我有一个用例,我在某个组件中有一个类似于vanilla html select的元素列表。我想,当用户点击列表中的任何元素时,路由应该改变。我可以使用反应路由器的一些API方法定义路由和更改路由时使用一些正则表达式,select的onValueChange事件吗?

实施例 根路线:/ 列表数据:猫,狗,大象

当有人点击Cat时我希望他导航到/ Cat,类似/ Dog,/ Elephant。

1 个答案:

答案 0 :(得分:1)

所以在谈了一下之后。弄清楚你想做什么。

您需要在react-router中定义一条新路由,您可以将其用于此历史记录更改..具体如下:

<Route exact path="/:name" component={SomeComponent} /> 

在您的组件中,您可以访问此&#34;名称&#34;通过this.props.params.name

您还可以在更新此路线之前调用操作来更新商店

注意:如果你继续使用v2 ......你应该让你的行为返回一个承诺,这样你就可以在你的组件中链接事件。又名:

onChange={this.handleChange}

handleChange = (value) => { // assuming you have the value here.. it may be e is the function param and you get the value as e.target.value
    this.props.saveSelectedAnimal(value).then( () => {
        this.props.history.push("/"); 
    })
}
相关问题