简体   繁体   中英

React - override redux prop by parent

Saying i have a Container connected to redux via:

const mapStateToProps = ({ MyReducer }) => ({
    myProp: MyReducer.myProp
});

Is it possible to force the value of myProp by the parent (override redux)?

I've tried:

<Container myProp={"notReduxValue"}/>

But mapStateToProps overrides the provided value.

NOTE: I can't change the container, my question is if it can be done via the parent only.

(Of course this implies a bad state design but unfortunately it has come to that)

Thanks

mapStateToProps accepts two arguments . So I guess you could override it by:

const mapStateToProps = ({ MyReducer }, { myProp }) => ({
  myProp: myProp || MyReducer.myProp,
})

In case you want to override myProp in an upper level, you can use connect 's mergeProps to do so (as @OrB also described).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM