【问题标题】:React router wont trigger componentWillUnmount when the route is a sub-route当路由是子路由时,React路由器不会触发componentWillUnmount
【发布时间】:2019-11-13 02:13:19
【问题描述】:

当路由是子路由时,我没有看到 react-router 卸载组件

因此,即使我在 path/1 和 path/2 之间切换,也不会为 ComponentForRoute 的实例调用 componentWillUnmount。有什么建议?这是 react-router 应该如何工作的吗?如果有,对处理路线变化有什么建议吗?

尝试使用 componentWillReceiveProps,但我猜它现在已弃用?

<Router history={history}>
    <Route path="path/:paramId" component={ComponentForRoute} />
</Router>

【问题讨论】:

  • 只需要捕获一个路由变化事件吗?
  • @Michele 我有一个名为posts 的页面,子页面如下:posts/newposts/popular 等,我正在尝试在子路线之间导航时重置状态,当前我正在尝试用 componentWillUnmount 重置,但它似乎没有触发
  • 尝试使用ComponentDidUpdate(prevProps)。您可以测试this.props.location !== prevProps.location(如果路线已更改,则为真)。另外,请确保使用 withRouter 包装组件
  • 嘿,谢谢你的回答,成功了。我还有一个问题,我正在使用async componentDidUpdate(prevProps){if (this.props.location !== prevProps.location) {await this.props.resetPosts(); this.props.fetchPosts(); }}。这是使用异步等待的不好方法吗?基本上我试图等待它在它获取新页面的状态之前重置。
  • 你可以做到。即使您可以摆脱 await,因为这是您执行的唯一呼叫。

标签: reactjs react-redux react-router react-router-dom


【解决方案1】:
componentDidUpdate (prevProps) {
    if (this.props.location !== prevProps.location) {
        //YOUR CODE HERE
    }
}

另外,组件必须用withRouter 包装。

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 2015-01-19
    • 2018-08-22
    • 1970-01-01
    • 2012-06-12
    • 2020-01-19
    • 2017-09-25
    • 2018-01-28
    相关资源
    最近更新 更多