[英]React - the value of state which depends on another state cannot be updated
重現步驟
預期行為
在allTypes
中,字段typeA
的值應該是"different value"
。
實際行為
字段typeA
的值仍然保持不變。
問題
typeA
的值不更新?應用程序.js
import "./styles.css";
import { useState, useEffect } from "react";
export default function App() {
const [typeA, setTypeA] = useState("01");
const [typeB, setTypeB] = useState("abc");
const [allTypes, setAllTypes] = useState({
typeA: [typeA],
typeB
});
console.log({ typeA }); // updated successfully
console.log({ allTypes }); // the value of typeA remain unchanged
return (
<div>
<button
onClick={() => {
setTypeA("different value");
}}
>
Update type A
</button>
</div>
);
}
代碼沙盒
https://codesandbox.io/s/jovial-lichterman-w1kbph?file=/src/App.js
useState 的參數是一個初始化器,它不會在初始渲染之后更新。 您可以useMemo
來實現您的預期行為。 您不能將值“提供”到 useState 的參數中。
const [typeA, setTypeA] = useState("01");
const [typeB, setTypeB] = useState("abc");
const allTypes = useMemo(() => {
return {typeA: [typeA], typeB}
},[typeA, typeB])
您也可以在沒有 useMemo 的情況下執行此操作,但是 object 引用將在每次渲染時重新創建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.