簡體   English   中英

反應 useState 不更新對象數組

[英]React useState not updating array of objects

我試圖在我的反應功能組件中使用useState來更新對象數組,但沒有任何反應。 這是我正在嘗試的代碼:

const countriesData = [
  { id: 1, name: "India", person: "Harpreet" },
  { id: 2, name: "Aus", person: "Monty" },
  { id: 3, name: "UK", person: "Preet" },
];

ReactDom.render(<App />, document.getElementById("root"));

function App() {
  const [name, setName] = useState(countriesData);
  const arr = [{ id: name.length + 1, name: "Pak", person: "Mnm" }];
  const AddMe = () => {
    setName({ ...name, ...arr });
  };
  return (
    <>
      <CountryName data={countriesData} />
      <button onClick={AddMe}> Add me</button>
    </>
  );
}

function CountryName({ data }) {
  return (
    <React.Fragment>
      {data.map((element, index) => (
        <div key={index}>
          <h1>{element.person}</h1>
          <span>from : {element.name}</span>
        </div>
      ))}
    </React.Fragment>
  );
}

我是 React 的新手。 我還嘗試將prevState作為setName參數,然后添加setName(prevState{...pevState, ...arr }); 已經看過這么多資源,但沒有運氣。 任何幫助將不勝感激。 謝謝!

初始數據是一個數組,請參閱countriesData變量,也在setName中嘗試使用{}

您應該使用[]而不是{}調用:

setName([ ...name, ...arr ]);

你需要做:

setName([ ...name, ...arr ]);

要么

setName((prev) => [...prev, ...arr]);

並更新數據:

<CountryName data={name} />

這是完整的代碼:

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

const countriesData = [
  { id: 1, name: "India", person: "Harpreet" },
  { id: 2, name: "Aus", person: "Monty" },
  { id: 3, name: "UK", person: "Preet" }
];
function CountryName({ data }) {
  return (
    <React.Fragment>
      {data.map((element, index) => (
        <div key={index}>
          <h1>{element.person}</h1>
          <span>from : {element.name}</span>
        </div>
      ))}
    </React.Fragment>
  );
}
export default function App() {
  const [name, setName] = useState(countriesData);

  const arr = [{ id: name.length + 1, name: "Pak", person: "Mnm" }];
  const AddMe = () => {
    setName((prev) => [...prev, ...arr]);
  };
  return (
    <>
      <CountryName data={name} />
      <button onClick={AddMe}> Add me</button>
    </>
  );
}


這是演示:https://codesandbox.io/s/keen-buck-ue9sn?file=/src/App.js:0-826

暫無
暫無

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

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