onEtern prop in react-router v4 [英] onEnter prop in react-router v4
问题描述
我正在使用 react-router v4
。我发现当我点击< Link>
组件时,路由会立即更改,这让我感到困惑。我想在获取数据之前保持当前路由,而不是切换路由然后获取数据。我发现在 react-router v3
中有一个 onEnter
钩子,但现在在反应 - 路由器v4
,它已被弃用。那么如何在点击< Link>
组件之后和路线更改之前立即获取数据?
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?
示例:
它是:at A
- >点击< LINK>到B
- >获取 B的数据
- >渲染 B
it's: at A
-> click at <Link> to B
-> fetching data for B
-> render B
not:at A
- >点击< Link>到B
- >渲染路线B
- >获取 B的数据
- >重新渲染 B
not: at A
-> click at <Link> to B
-> render Route B
-> fetching data for B
-> rerender B
推荐答案
在 react-router v4
,你可以使用 render
prop到 Route
来替换 onEnter
react-router v3中存在的功能
In react-router v4
, you can make use of render
prop to Route
to replace the onEnter
functionality existing in react-router v3
假设您有类似的路线在 react-router v3
Suppose you have a route like in react-router v3
<Route path="/" component={Home} onEnter={getData} />
react-router v4中的等价物
将
<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
.
来自 Github讨论 :
From the Github discussion:
We have no lifecycle hooks that receive props on initial render.
我们不再拥有路线生命周期。相反,由于< Match>
组件是真正的组件(不是像s
那样的伪组件),他们可以参与React的生命周期,意味着他们
只能使用 componentWillMount
。
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是关于仅作为组件的路由。这意味着利用
生命周期方法。
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)
}
}
这篇关于onEtern prop in react-router v4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!