react-router v4 中的 onEnter 属性 [英] onEnter prop in react-router v4
问题描述
我正在使用 react-router v4
.我发现当我点击 组件时,路线会立即改变,这很令人困惑.我想在获取数据之前停留在当前路由,而不是切换路由然后获取数据.我发现在
react-router v3
中有一个 onEnter
钩子,但现在在 react-router v4
中,它已被弃用.那么如何在我点击 <Link>
组件之后和路由改变之前获取数据?
示例:
它是:在 A
-> 点击 to B
-> 为 B
获取数据 -> 渲染 B
不是:在 A
-> 点击 to B
-> 渲染 Route B
-> 为 B
获取数据 -> 重新渲染 B
在 react-router v4
中,你可以使用 render
属性给 Route
替换 react-router v3
onEnter
功能假设你有一个类似于 react-router v3
在 react-router v4
中的等价物是
<路由精确路径="/" render= {() =>{获取数据();return <Home data={this.state.data}/>}}/>
然而,建议的方法是利用 component
中的 lifecycle
方法.
来自 Github 讨论:
<块引用>我们没有在初始渲染时接收道具的生命周期钩子.
我们不再有路由生命周期".相反,由于
组件是真正的组件(不是像 s 这样的伪组件是)他们可以参与 React 的生命周期,这意味着他们可以只使用 componentWillMount
.
所以建议的解决方案之一是:
<块引用>v4 是关于路由只是组件.这意味着利用生命周期方法.
componentWillMount() {//或 componentDidMount获取(this.props.match.params.id)}componentWillReceiveProps(nextProps) {//或 componentDidUpdateif (nextProps.match.params.id !== this.props.match.params.id) {获取(nextProps.match.params.id)}}
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
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 usecomponentWillMount
.
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) } }
这篇关于react-router v4 中的 onEnter 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!