组件更新状态后没有return新元素?

Component doesn't return the new elements after updating state?

我有 3 个元素,我想通过单击任何一个来添加一个新元素 div,但问题是在将新元素添加到数组后,它们不会从组件中呈现出来。

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  let elements = [
    { id: 0, text: "first" },
    { id: 1, text: "second" },
    { id: 2, text: "third" }
  ];
  const [state, setstate] = useState(elements);
  function handleClick() {
    elements.push({ id: 3, text: "xxx", checkBox: null });
    setstate(elements);
    console.log(state); //state shows 4 elememnt but they don't render in 
  }

  return (
    <div className="App">
      {state.map((e) => (
        // why this don't render the new elements?
        <div onClick={handleClick}>{e.text}</div>
      ))}
    </div>
  );
}

in codesandbox https://codesandbox.io/s/beautiful-silence-c1t1k?file=/src/App.js:0-641

您应该不要直接改变状态,这不是一个好习惯。改为尝试:

function handleClick() {
    setstate(prevState => [
       ...prevState,
       { id: 3, text: "xxx", checkBox: null }
    ])
}

通过这样做,您将克隆数组的先前状态并将该新元素添加到数组的副本中,您可以将其传递给 setState 函数。

查看工作 CodeSandbox here

你不应该直接改变状态

import React, { useState } from "react";
import "./styles.css";

const defaultElements = [
  { id: 0, text: "first" },
  { id: 1, text: "second" },
  { id: 2, text: "third" }
];

const newElement = {
  id: 3,
  text: "xxx",
  checkBox: null
};

export default function App() {
  const [state, setState] = useState(defaultElements);

  function handleClick() {
    setState((item) => [...item, newElement]);
  }

  return (
    <div className="App">
      {state.map(({ text }, index) => (
        <div key={index} onClick={handleClick}>
          {text}
        </div>
      ))}
    </div>
  );
}