onEnter prop in react-router v4

后端 未结 1 2018
南笙
南笙 2020-12-10 08:50

I\'m using react-router v4. I find it confusing that when I click on component, the route is immediately changed. I want to stay at th

相关标签:
1条回答
  • 2020-12-10 09:38

    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)
      }
    }
    
    0 讨论(0)
提交回复
热议问题