我有两个使用相同组件(表单)的路由,一个用于创建新条目,另一个用于编辑.来自React Router的状态名称
has been removed,我不能只检查this.route.name ===’edit’=>取(itemAPI).
一个选项是编写reducer / action来在我的redux商店中创建“编辑”状态,但我想知道这是否是最佳实践,并且是否有更简单的方法来检查我在应用程序中的位置(哪条路线).
我的路线:
<Route component={ItemNew} path='/items/edit/:id' />
<Route component={ItemNew} path='/items/new' />
在我的ItemNew组件中,我想:
componentDidMount () {
let stateName = this.props.location.state
if(stateName === 'edit') {
this.props.fetchItem() // dispatch API action
}
}
最佳答案 用于在当前URL上执行匹配的最后部分的Route组件显示在this.props.route上;参与匹配的整个嵌套路由列表位于this.props.routes数组中.您可以将任意道具传递到这些路径上,并在以后检索它们.例如:
<Route component={ItemNew} name="edit" path='/items/edit/:id' />
<Route component={ItemNew} name="add" path='/items/new' />
和
componentDidMount () {
if(this.props.route.name === 'edit') {
this.props.fetchItem() //dispatch API action
}
}