[英]How does React useState hook work with mutable objects
Let's say my component has a piece of state that is a set of selected IDs. 假设我的组件有一段状态,它是一组选定的ID。 Javascript has a
Set
type, so I try this: Javascript有一个
Set
类型,所以我试试这个:
let [selectedIDs, setSelectedIDs] = useState(new Set());
The Javascript Set
is itself mutable, so I'm confused. Javascript
Set
本身是可变的,所以我很困惑。
function toggleSelectedID(id) {
let set = selectedIDs;
if (set.has(id)) { set.delete(id) }
else { set.add(id) }
// ???
setSelectedIDs(set);
}
If the Set
objects where immutable, I would create a new Set
with the added or removed element, and pass that new Set
to setSelectedIDs
, changing the state at that point. 如果
Set
对象Set
不可变的,我将使用添加或删除的元素创建一个新的Set
,并将该新的Set
传递给setSelectedIDs
,从而更改该点的状态。
But with the mutable Set
, what would happen if we returned at the ???
但是对于可变的
Set
,如果我们返回???
会发生什么???
line? 线? Would React be in a bad state, because I "reached into" its state and mutated it without officially telling it about it with
setSelectedIDs
? React是否处于糟糕的状态,因为我“进入”其状态并且在没有用
setSelectedIDs
正式告知它的情况下对其进行了改变?
In your example, setSelectedIDs
not updating application state
. 在您的示例中,
setSelectedIDs
不更新应用程序state
。
That's because you set the same reference, you should make a copy: 那是因为你设置了相同的引用,你应该复制一下:
setSelectedIDs(new Set(set));
codesandbox example. codesandbox示例。
What would happen if we returned at the ???
如果我们回到???会怎么样? line
线
Nothing would happen, you just changed a variable in your function, you can do it as many times you like. 什么都不会发生,你刚刚改变了函数中的一个变量,你可以多次这样做。
When you want your React-App to notice the change, you should then call a function the updates the state ( setSelectedIDs()
) and your app will be rerendered. 当您希望React-App注意到更改时,您应该调用一个函数来更新状态(
setSelectedIDs()
)并且您的应用程序将被重新呈现。
Refer to Using State Correctly 请参阅正确使用状态
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.