簡體   English   中英

反應 state 的奇怪隱式突變

[英]React weird implicit mutation of state

我有 TaskManager 組件,其中有 state

const [sections, setSections] = useState({
sectionArr: [/*some stuff*/],
taskArr: [/*some stuff*/],
})

和一堆conlole.log s

  console.log("Sections is", sections);
  console.log("Type: ", typeof sections);

我還有 AddSectionButton,它基本上是一個添加新部分的按鈕。 它是 onClick 回調 function 是

  const handleClick = () => {
    const newObject = {
      name: "added section",
      id:
        // random id
        Math.floor(Math.random() * (Number.MAX_VALUE - 0)) + 0,
      position: 0,
    };
    const sectionsCopy = sections;
    const updatedState = sectionsCopy.sectionArr.push(newObject);

    setSections(updatedState);
  };

當我首先運行我的應用程序時一切正常, my console.log s output 是正確的

Sections is {sectionArr: Array(3), taskArr: Array(3)}
Type:  object
(3) [{…}, {…}, {…}]
ƒ map() { [native code] }

但是當我點擊我的 AddSectionButton 時 - output 變得非常奇怪

Sections is 4
Type:  number

我沒有辦法用 4 改變我的整個 state。關於為什么我的 state 改變的任何想法?

ray#push 方法在原地工作,您不必將其分配給新變量。 它不會返回一個新數組,但會修改原始數組並返回它的長度。 這就是為什么你會得到一個數字作為結果。

我會做這樣的事情而不是使用推送

updateState = { sectionArr: [...sectionsCopy.sectionArr, newObject], taskArr: [...sectionsCopy.taskArr] }

甚至可能使用sectionCopy 變量傳遞給setSections,因為使用push 會改變該變量並返回數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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