简体   繁体   中英

how does react props merge state passed from parent component and redux store

I my case, my child component needs to get a state named like myDepartment. If I use @connect to fetch that variable from redux (let's say the value here is 'deptA') and pass another variable with the same name(with value 'deptB') from parent component props, what is the value of myDepartment in the child component?

Props mapped using connect override ones passed from the parent with the same name. So in your example myDepartment would always have value deptA .

Just to clarify with some code:

const MyComponent = connect((state) => ({
  myDepartment: state.myDepartment // 'deptA'
}))((props) => (
  <div>{props.myDepartment}</div>
))

// always renders <div>deptA</div>
const Wrapper = () => (
  <MyComponent myDepartment="deptB" /> 
)

Having tried it, it looks as though redux would take priority over a parent:

https://codesandbox.io/s/aged-violet-uoeg6?file=/src/App.js

However, if you were to use the new useSelector react-redux hook (instead of connect) and not destructure props, they would co exist as sharedProp and props.sharedProp (ChildTwo example in sandbox). If you destructure props as {sharedProp}, then you would not be able to create a variable named sharedProp to store the useSelector return.

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