小编典典

react-router v4中的onEnter prop

reactjs

我正在使用react-router v4。我感到困惑的是,当我单击<Link>组件时,路线会立即更改。我想在获取数据之前停留在当前路线,而不是先切换路线再获取数据。我发现其中react- router v3有一个onEnter钩子,但现在在中react-router v4,它已被弃用。那么,如何在单击<Link>组件之后以及更改路线之前立即获取数据?

例:

它是:在A->单击<Link> to B->获取数据以进行B->渲染B

不:在A->单击<Link> to B->渲染Route B->获取数据B->重新渲染B


阅读 257

收藏
2020-07-22

共1个答案

小编典典

在中react-router v4,您可以使用renderprop Route来替换其中onEnter现有的功能react-router v3

假设您有一条类似的路线 react-router v3

<Route path="/" component={Home} onEnter={getData} />

这的等效react-router v4

<Route exact path="/" render= {() => {getData(); return <Home data={this.state.data}/>}} />

但是,建议的方法是利用中的lifecycle方法component

Github讨论中

We have no lifecycle hooks that receive props on initial render.

我们不再有“路线生命周期”。相反,由于<Match>
组件是真实组件(不是像s这样的伪组件),因此它们可以参与React的生命周期,这意味着它们可以使用componentWillMount

因此,建议的解决方案之一是:

v4只是关于路由的组成部分。这意味着要利用生命周期方法。

componentWillMount() { // or componentDidMount
  fetch(this.props.match.params.id)
}

componentWillReceiveProps(nextProps) { // or componentDidUpdate
  if (nextProps.match.params.id !== this.props.match.params.id) {
    fetch(nextProps.match.params.id)
  }
}
2020-07-22