【问题标题】:Component doesn't return the new elements after updating state?更新状态后组件不返回新元素?
【发布时间】:2020-09-14 11:07:32
【问题描述】:

我有 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 codesandboxhttps://codesandbox.io/s/beautiful-silence-c1t1k?file=/src/App.js:0-641

【问题讨论】:

    标签: javascript arrays reactjs react-hooks rendering


    【解决方案1】:

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

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

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

    查看工作中的 CodeSandbox here。

    【讨论】:

    • 啊哈,谢谢......另外,你知道如何将 { id: 0, text: "first" } 更新为 { id: 0, text: "update." }?
    【解决方案2】:

    您应该不要直接改变状态

    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>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-23
      • 2016-11-20
      • 1970-01-01
      • 2018-02-20
      • 2022-01-17
      • 2019-06-17
      • 1970-01-01
      • 2019-07-09
      相关资源
      最近更新 更多