【问题标题】:onEnter prop in react-router v4react-router v4 中的 onEnter 属性
【发布时间】:2018-01-07 20:33:39
【问题描述】:

我正在使用react-router v4。我发现当我单击<Link> 组件时,路由立即更改,这让我感到困惑。我想在获取数据之前停留在当前路线,而不是切换路线然后获取数据。我发现在react-router v3 中有一个onEnter 钩子,但现在在react-router v4 中,它已被弃用。那么如何在点击<Link> 组件之后,在路由更改之前获取数据呢?

示例:

它是:A -> 点击<Link> to B -> 获取B 的数据 -> 渲染B

不是:A -> 点击<Link> to B -> 渲染Route B -> 获取B 的数据 -> 重新渲染B

【问题讨论】:

    标签: javascript reactjs react-router frontend


    【解决方案1】:

    react-router v4中,你可以使用render prop to Route来替换onEnter中存在的react-router v3功能

    假设你有一条类似react-router v3的路线

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

    react-router v4 中的等价物是

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

    但是建议的方法是使用component 中的lifecycle 方法。

    来自Github discussion

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

    我们不再有“路线生命周期”。相反,因为&lt;Match&gt; 组件是真实组件(不是像 s 这样的伪组件 是)他们可以参与 React 的生命周期,这意味着他们 可以使用componentWillMount

    所以建议的解决方案之一是:

    v4 只是将路由作为组件。这意味着利用 生命周期方法。

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

    【讨论】:

    • 我并不是要替换 onEnter。例如,在您的代码中,getData() 可能需要 1 秒或更长时间。但是, 在数据返回之前返回。所以你在 { Home } 并等待数据。我要做的是在渲染 之前,获取数据,然后切换到 { Home }。
    • @ONIAKI,不幸的是 v4 没有这样的功能。 Github 讨论中给出了一些方法。鼓励使用生命周期钩子来获取数据
    • 这很令人困惑。我理解他们的理念,但它阻碍了一些与用户互动的方式。嗯...我用过 vue.js 和 vue-router 可以做到我所说的。在找到好的解决方案之前,也许我应该考虑切换到 react-router v3。
    • 确实如此,但我们需要找到解决方法
    • 我想我找到了正确的方法。使用 history.push() 可以以编程方式更改路由,因此我可以在更改路由之前获取一些数据。
    猜你喜欢
    • 2017-09-04
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    相关资源
    最近更新 更多