【发布时间】: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/new、posts/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