React useState hook 如何处理可变对象 [英] How does React useState hook work with mutable objects

查看:58
本文介绍了React useState hook 如何处理可变对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的组件有一个状态,它是一组选定的 ID.Javascript 有一个 Set 类型,所以我试试这个:

let [selectedIDs, setSelectedIDs] = useState(new Set());

Javascript Set 本身是可变的,所以我很困惑.

function toggleSelectedID(id) {让 set = selectedIDs;if (set.has(id)) { set.delete(id) }其他{ set.add(id) }//???setSelectedIDs(set);}

如果 Set 对象不可变,我会用添加或删除的元素创建一个新的 Set,并将新的 Set 传递给setSelectedIDs,改变当时的状态.

但是对于可变的 Set,如果我们在 ??? 行返回会发生什么?React 是否会处于糟糕的状态,因为我进入"了它的状态并在没有用 setSelectedIDs 正式告诉它的情况下改变了它?

解决方案

在您的示例中,setSelectedIDs 未更新应用程序 state.

那是因为你设置了相同的引用,你应该复制一份:

setSelectedIDs(new Set(set));

codesandbox 示例.

<小时><块引用>

如果我们在 ??? 行返回会发生什么

什么都不会发生,你只是在你的函数中改变了一个变量,你可以随意多次这样做.

当您希望您的 React-App 注意到更改时,您应该调用一个函数来更新状态 (setSelectedIDs()),您的应用将被重新渲染.

参考正确使用状态

Let's say my component has a piece of state that is a set of selected IDs. Javascript has a Set type, so I try this:

let [selectedIDs, setSelectedIDs] = useState(new Set());

The Javascript Set is itself mutable, so I'm confused.

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.

But with the mutable Set, what would happen if we returned at the ??? 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?

解决方案

In your example, setSelectedIDs not updating application state.

That's because you set the same reference, you should make a copy:

setSelectedIDs(new Set(set));

codesandbox example.


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.

Refer to Using State Correctly

这篇关于React useState hook 如何处理可变对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆