【问题标题】:migrating react-router v2 to v4 onEnter arguments将 react-router v2 迁移到 v4 onEnter 参数
【发布时间】:2017-10-04 15:41:14
【问题描述】:

我正在将一个应用程序(不是我编写的)从 react-router v2 迁移到 v4。

旧的 v2 代码如下所示:

<Route path="/configurations/:id" onEnter={loadConfiguration}>
    // some stuff
</Route>

新的 v4 代码如下所示:

<Route path="/configurations/:id" component={MyComponent}>
    // some stuff
</Route>

export default class MyComponent extends Component {
  componentDidMount() {
    loadConfiguration()
  }
  // render method, etc
}

问题是在 v2 中 loadConfiguration 函数是用 3 个参数调用的——nextState、replace、callback

在 v4 代码中,调用 loadConfiguration 函数时参数为 0。

从 v2 迁移到 v4 时,如何将相同的值传递给 loadConfiguration?

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    您可以使用 render 将道具传递给您的组件:

    <Route path="/configurations/:id" render={
      () => <MyComponent nextState={ nextState } replace={ replace } callback={ callback } />
    } />
    

    然后在你的组件中:

    export default class MyComponent extends Component {
    
      loadConfiguration() {
        ...
      }
    
      componentDidMount() {
        this.loadConfiguration(this.props.example, this.props.replace, this.props.callback)
      }
    
      // render method, etc
    
    }
    

    如果需要,您还可以从父级传递 loadConfiguration 函数作为道具,然后在您的组件中将其调用为 this.props.loadConfiguration()


    注意:您也可以从父级传递道具:

    <Route path="/configurations/:id" render={
      (props) => <MyComponent example={ props.example } />
    } />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2017-09-04
      • 2018-01-07
      • 2017-09-14
      • 2016-06-27
      • 2018-02-10
      • 2017-10-04
      相关资源
      最近更新 更多