【问题标题】:Route state name in React+ReduxReact+Redux 中的路由状态名称
【发布时间】:2016-04-06 21:40:03
【问题描述】:

我有 2 条使用相同组件(表单)的路线,一条用于创建新条目,另一条用于编辑。来自 React Router 的状态名称 has been removed,我不能只检查 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
    }
}

【问题讨论】:

    标签: javascript reactjs react-router redux


    【解决方案1】:

    用于在当前 URL 上执行匹配的最后部分的 Route 组件显示在 this.props.route 上;参与比赛的嵌套Routes 的整个列表在this.props.routes 数组中。您可以将任意道具传递到这些 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
      }
    }
    

    【讨论】:

    • @alexndm 默认情况下不是。使用钩子(如onEntercomponentDidMount)将其推入状态,或查看redux-simple-routerredux-router 之类的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2021-10-16
    • 1970-01-01
    • 2017-04-27
    • 2018-07-01
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多