gpt4 book ai didi

javascript - React+Redux 中的路由状态名

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:14:45 25 4
gpt4 key购买 nike

我有 2 条路线使用相同的组件(表单),一条用于创建新条目,另一条用于编辑。国名has been removed从 React Router,我不能只检查 this.route.name === 'edit' => fetch(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
}
}

最佳答案

Route 组件用于执行当前 URL 匹配的最后部分显示在 this.props.route 上;参与匹配的整个嵌套 Route 列表在 this.props.routes 数组中。您可以将任意 Prop 传递到这些 Route 上并稍后检索它们。例如:

<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
}
}

关于javascript - React+Redux 中的路由状态名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34571450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com