簡體   English   中英

React - 無法更新依賴於另一個 state 的 state 的值

[英]React - the value of state which depends on another state cannot be updated

重現步驟

  1. 進入Codesandbox控制台后,可以看到typeAallTypes的初始值。
    在此處輸入圖像描述
  2. 單擊“更新類型 A”按鈕
  3. 在控制台中,您可以看到typeAallTypes的更新值。
    在此處輸入圖像描述

預期行為
allTypes中,字段typeA的值應該是"different value"

實際行為
字段typeA的值仍然保持不變。

問題

  1. 為什么字段typeA的值不更新?
  2. 如何解決?

應用程序.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM