admin管理员组文章数量:1326118
I'm using react-router v4
. I find it confusing that when I click on <Link>
ponent, 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>
ponent 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
I'm using react-router v4
. I find it confusing that when I click on <Link>
ponent, 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>
ponent 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 Answer
Reset to default 6In 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="/" ponent={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 ponent
.
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>
ponents are real ponents (not pseudo-ponents like s were) they get to participate in React's lifecycle, which means they can just useponentWillMount
.
So one of the suggested solution is:
v4 is all about routes just being ponents. That means taking advantage of lifecycle methods.
ponentWillMount() { // or ponentDidMount fetch(this.props.match.params.id) } ponentWillReceiveProps(nextProps) { // or ponentDidUpdate if (nextProps.match.params.id !== this.props.match.params.id) { fetch(nextProps.match.params.id) } }
本文标签: javascriptonEnter prop in reactrouter v4Stack Overflow
版权声明:本文标题:javascript - onEnter prop in react-router v4 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742192167a2430415.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论