说我有一个 Container
通过以下方式连接到 redux:
const mapStateToProps = ({ MyReducer }) => ({
myProp: MyReducer.myProp
});
是否可以通过父级强制 myProp 的值(覆盖 redux)?
我试过:
<Container myProp={"notReduxValue"}/>
但是 mapStateToProps
会覆盖提供的值。
注意:我无法更改容器,我的问题是是否只能通过父容器来完成。
(当然这意味着糟糕的状态设计,但不幸的是它已经到了那个地步)
谢谢
最佳答案
mapStateToProps
接受 two arguments .所以我想你可以通过以下方式覆盖它:
const mapStateToProps = ({ MyReducer }, { myProp }) => ({
myProp: myProp || MyReducer.myProp,
})
如果你想在上层覆盖myProp
,你可以使用connect
的mergeProps
来实现(如@OrB也有描述)。
const mapStateToProps = ({ MyReducer }, { myProp }) => ({
myProp: MyReducer.myProp,
})
const mapDispatchToProps = () => ({ ... })
const mergeProps = (stateProps, dispatchProps, ownProps) => ({
... // make your changes here
})
const ConnectedContainer = connect(
mapStateToProps,
mapDispatchToProps,
mergeProps
)(Container)
关于javascript - React - 由父级覆盖 redux prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46523750/