【发布时间】: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 && state.page.title 但这会在我的代码中到处引入大量的保护。
如果父级已经卸载,我如何防止最后一次连接 mapStateToProps 发生(因此不需要对子级进行 prop 更改,因为无论如何它都会被卸载)。
【问题讨论】:
-
如果你使用
composefromredux,它会从右到左组合函数。您是否尝试过颠倒订单?
标签: reactjs react-redux