[英]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.我的情况是,我的子组件需要获得一个名为 myDepartment 的 state。 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?
如果我使用@connect 从 redux 获取该变量(假设这里的值是'deptA')并从父组件道具传递另一个具有相同名称的变量(值为'deptB'),那么 myDepartment 在子组件?
Props mapped using connect
override ones passed from the parent with the same name.使用
connect
映射的道具会覆盖从具有相同名称的父级传递的道具。 So in your example myDepartment
would always have value deptA
.因此,在您的示例中,
myDepartment
始终具有值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:尝试过之后,看起来 redux 会优先于父母:
https://codesandbox.io/s/aged-violet-uoeg6?file=/src/App.js 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).但是,如果您要使用新的 useSelector react-redux 钩子(而不是连接)而不是解构道具,它们将作为 sharedProp 和 props.sharedProp 共存(沙盒中的 ChildTwo 示例)。 If you destructure props as {sharedProp}, then you would not be able to create a variable named sharedProp to store the useSelector return.
如果你将 props 解构为 {sharedProp},那么你将无法创建一个名为 sharedProp 的变量来存储 useSelector 返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.