NextJs Typescript - 调用 setState 时组件不会更新

NextJs Typescript - the component does not update when setState called

我有以下使用 Typescript 的下一页代码:

import { NextPage } from "next";
import { useState } from "react";

const Test: NextPage = () => {
  const initList = ["a", "b", "c"];
  const [list, setList] = useState<Array<String>>(initList);
  const handleClick = () => {
      var listTemp = list;
      listTemp.push("z");
      setList(listTemp);
  }
  return (
    <div>
      {list.map((item) => (
        <h1>{item}</h1>
      ))}
      <button onClick={handleClick}>
          Button
      </button>
    </div>
  );
};

export default Test;

我预期的行为是当我单击按钮时 list 在呈现页面时展开。 但是很明显,状态已经改变了,但是组件没有。

这里是不是对我有什么误解?

您正在改变状态对象。

const handleClick = () => {
  var listTemp = list; // <-- listTemp is reference to list state
  listTemp.push("z");  // <-- mutates the array
  setList(listTemp);   // <-- save same reference back into state
}

问题是从未创建新的数组引用,因此 React 不会“看到”状态实际上已更新。

创建数组的浅表副本并将新元素追加到创建的新数组引用中。

const handleClick = () => {
  setList(list => [...list, "z"]); 
}

** 当你控制 listTemp 时什么也不会发生。*

const listTemp = list -------------> not work;

const listTemp = [...list] --------> will work fine;

现在 listTemp 具有所有列表数组值。

const listTemp = [...list, 'z'] -------> Ans ["a", "b", "c", "z"];