gpt4 book ai didi

reactjs - 与 Prop 冲突

转载 作者:行者123 更新时间:2023-12-03 14:06:41 25 4
gpt4 key购买 nike

如果我们在调用组件时传递一个 prop 并且将 map 状态传递给 props,会发生什么

<Modal foo={1} ... />

const Modal = ({ foo, ... }) => {
console.log(foo) // 1 or 2 ? and Why ? is it random ?
}

export default connect(
(state) => ({
foo: state.foo, // let's say the value in the reducer is 2
...
})
)(Modal)

有规律还是随机的?

最佳答案

connect 是一个 HOC,它将从 mapStateToPropsmapDispatchToProps 接收到的值传递给组件。

mapStateToPropsmapDispatchToProps 传递的值将覆盖传递给组件的 props。

因此,在上述情况下,console.log({foo}) 将记录 2

<小时/>

为了更好地理解它,您可能会想到在connect like中使用Component

<Component {...ownProps} {...valuesFromConnectArgs} />
<小时/>

您还可以查看connect code from react redux其中有以下方法来 mergeProps

export function defaultMergeProps(stateProps, dispatchProps, ownProps) {
return { ...ownProps, ...stateProps, ...dispatchProps }
}

您可以查看demo here

关于reactjs - 与 Prop 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55138857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com