将 react-router v2 迁移到 v4 onEnter 参数

migrating react-router v2 to v4 onEnter arguments

我正在将一个应用程序(不是我写的)从 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?

您可以使用 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 函数作为 prop,然后在您的组件中将其调用为 this.props.loadConfiguration()


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

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