gpt4 book ai didi

javascript - Javascript ES6 类应该用作 React State 吗?

转载 作者:行者123 更新时间:2023-11-30 19:10:07 26 4
gpt4 key购买 nike

ES6类应该直接用作React状态吗?

我想定义一个 ES6 类:

  1. 具有将显示在前端的成员变量。 (对它们的更改会触发重新渲染)
  2. 具有在这些成员变量发生变化时定期将其与我的后端同步的方法。

但是,调用 setState 似乎不会区分类成员,至少据我所知。

使用以下类:

class Document{
constructor(){
this.title = "";
this.body = "";
}


syncWithDatabase = async () => {
// do some logic to update the database
}

}

这个组件:


// import Document from "...";

export default function Sandbox() {
const [document, setDocument] = useState(new Document());
const [renderTrigger, setRenderTrigger] = useState(false);

return (
<div>
<div>{document.title}</div>
<div>{document.body}</div>
<button
onClick={() => {
document.title = 'Some Default Title';
document.body = 'lorem text';
document.syncWithDatabase(); // being able to take this type of action in this way is why I'm trying to use classes.
setDocument(document);
}}
>
Set Canned Data
</button>

<div>Render trigger is: {renderTrigger ? 'true' : 'false'}</div>
<button onClick={() => setRenderTrigger(true)}>Force Render</button>

</div>
);
}

单击第一个按钮将在保持 react 状态的 Document 实例上设置标题和正文,但它不会更新 UI。

单击第二个按钮以我确信有效的方式强制重新渲染,会使 document 的更新成员渲染出来,即使在 setDocument< 时它们没有渲染出来 被调用。

使用new Document()创建一个新对象并将其传递给setDocument将触发重新渲染。所以我认为 React 没有进行深度比较,或者看到对 Document 对象的引用没有改变,因此没有重新渲染。

那么,是否可以更改对象的成员,将该对象传递给 setState Hook 并让它更新 UI,而无需创建全新的对象?或者我应该避免做我在这里想做的事情吗?

最佳答案

可以(但可能不应该,见下文)使用由构造函数创建的对象(这就是代码中的document)作为状态。您不能做的就是直接在此处修改它(请参阅 the documentation ):

document.title = 'Some Default Title'; // <=== INCORRECT
document.body = 'lorem text'; // <=== INCORRECT
document.syncWithDatabase();
setDocument(document); // <=== INCORRECT

相反,您需要创建一个文档对象

const newDoc = new Document();
newDoc.title = 'Some Default Title';
newDoc.body = 'lorem text';
newDoc.syncWithDatabase();
setDocument(newDoc);

也就是说,当使用 useState 钩子(Hook)时,通常最好保持状态变量离散(一个用于 title 一个用于 body),这样更改一个就不需要同时更改另一个(当然,除非它们总是一起更改)。该文档讨论了 here ;这里引用一段话:

...we recommend to split state into multiple state variables based on which values tend to change together.

(他们的重点)

关于javascript - Javascript ES6 类应该用作 React State 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58581830/

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