【问题标题】:Preventing child prop update if parent component unmounts如果父组件卸载,防止子道具更新
【发布时间】:2019-04-10 08:02:36
【问题描述】:

升级到最新的 react-redux (v7) 后,我遇到了 prop 更新问题。这是一个例子:

const shouldRender = WrappedComponent => props => props.shouldRender ? <WrappedComponent {...props} /> : null

const MyComponent = compose(
  connect(state => ({ shouldRender: Boolean(state.page) })),
  shouldRender,
  connect(state => ({ title: state.page.title }))
)(MyBaseComponent)

<MyComponent />

store.dispatch({ type: 'CLEAR_STATE' }) // => Sets state.page to null

在 react-redux v5 中,当 state.page 重置为初始状态(null)时,shouldRender HOC 将渲染 null 而不是组件,因此不会尝试获取 state.page.title 中的下一行。

升级到v7后,同样的场景还是会触发state.page.title并抛出错误(cannot get title of undefined)。

最简单的解决方案是不依赖父 HOC 并保护 props (title: state.page &amp;&amp; state.page.title 但这会在我的代码中到处引入大量的保护。

如果父级已经卸载,我如何防止最后一次连接 mapStateToProps 发生(因此不需要对子级进行 prop 更改,因为无论如何它都会被卸载)。

【问题讨论】:

  • 如果你使用compose from redux,它会从右到左组合函数。您是否尝试过颠倒订单?

标签: reactjs react-redux


【解决方案1】:

我通过升级到 7.0.3 修复了它

【讨论】:

    猜你喜欢
    • 2019-12-18
    • 2017-07-10
    • 2021-02-27
    • 2016-01-14
    • 2021-02-09
    • 1970-01-01
    • 2018-10-01
    • 2023-01-10
    • 1970-01-01
    相关资源
    最近更新 更多