onEnter prop in react-router v4

五迷三道 提交于 2019-11-27 03:45:47

问题


I'm using react-router v4. I find it confusing that when I click on <Link> component, the route is immediately changed. I want to stay at the current route before I fetch the data, not to switch the route and then fetch the data. I find that in react-router v3 there's a onEnter hook, but now in react-router v4, it is deprecated. So how can I fetch data right after I click on <Link> component and before the route is changed?

Example:

it's: at A -> click at <Link> to B -> fetching data for B -> render B

not: at A -> click at <Link> to B -> render Route B -> fetching data for B -> rerender B


回答1:


In react-router v4, you can make use of render prop to Route to replace the onEnter functionality existing in react-router v3

Suppose you have a route like in react-router v3

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

The Equivalent of this in react-router v4 would be

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

However the suggested method is to make use of lifecycle methods in the component.

From the Github discussion:

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

We no longer have a "route lifecycle". Instead, since <Match> components are real components (not pseudo-components like s were) they get to participate in React's lifecycle, which means they can just use componentWillMount.

So one of the suggested solution is:

v4 is all about routes just being components. That means taking advantage of lifecycle methods.

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


来源:https://stackoverflow.com/questions/45429963/onenter-prop-in-react-router-v4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!