简体   繁体   English

用于初始化 useState 钩子的传入属性在调用钩子的更新程序方法时得到更新

[英]Passed-in prop used to initialize a useState hook gets updated when calling the hook's updater method

Given the following code:给定以下代码:

const MyComponent = ({ myObj }) => {
    const [myStatefulObj, setMyStatefulObj] = useState(myObj.subObj)

    const handleChange = () => {
        const updatedObj = { newProperty: Math.random() }
        setMyStatefulObj(updatedObj) // myObj is updated too!
    }

    return <div />
}

I am trying to initialize a new local prop with useState , and hydrating its initial value with a prop that is passed in from a parent component.我正在尝试使用useState初始化一个新的本地 prop,并使用从父组件传入的 prop 对其初始值进行水合。

When I update my prop using setMyStatefulObj everything works fine, except that it's also updating the prop that's passed into the component.当我使用setMyStatefulObj更新我的道具时,一切正常,除了它也在更新传递给组件的道具。

This is an undesired side effect and one I haven't come across before.这是一种不受欢迎的副作用,我以前没有遇到过。

The prop that is getting passed in is from a parent that creates it with a selector from react-redux 's useSelector hook.传入的道具来自使用react-reduxuseSelector钩子中的选择器创建它的父级。

There are no actions being dispatched or anything, but simply logging the value of the myObj prop shows that it is indeed being updated every time the local setMyStatefulObj method gets called.没有任何动作被调度或任何东西,但简单地记录myObj属性的值表明它确实在每次调用本地setMyStatefulObj方法时被更新。

The effect you are describing doesn't make sense and I was not able to reproduce it.您描述的效果没有意义,我无法重现它。 Maybe you could create a snippet and share it.也许您可以创建一个片段并分享它。

I don't think that was caused by the hooks function.我不认为这是由钩子 function 引起的。

I have created a simple example in CodeSandBox as you said, and it obviously not reproduced.正如您所说,我在CodeSandBox中创建了一个简单的示例,显然没有复制。 You can edit this sandbox and try to simulate your situation maybe you can find the root cause.您可以编辑此沙箱并尝试模拟您的情况,也许您可以找到根本原因。

But since you are using redux, I would suggest you to use useSelector to select the state you need inside hooks function, then you would not have this kind of concern, and it will have better performance(if you pass the prop, every time myObj changes the hooks component will re-render). But since you are using redux, I would suggest you to use useSelector to select the state you need inside hooks function, then you would not have this kind of concern, and it will have better performance(if you pass the prop, every time myObj更改钩子组件将重新渲染)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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