简体   繁体   中英

Unable to update empty array with formdata

I am currently trying to store the data attached to buttons on the site when a user clicks on them. I am using onClick function to grab the data passed in from the button and I am attempting to set it in state. The issue I am running into; however, is that the state value is not updating for whatever reason and it remains an empty array. if the object exists in the array, update it.,更新它。 If it does not, append to the array. Any guidance as to why state is not updating properly would be greatly appreciated. My code is as follows:

import { useState } from "react";

export default function App() {
  const [formData, setFormData] = useState([]);
  const data = [
    { name: "test1", id: 1, isActive: false },
    { name: "test2", id: 2, isActive: false }
  ];

  const handleClick = (item) => {
    setFormData(
      (formData) =>
        formData.map((res) =>
          res?.id === item.id
            ? { ...res, checked: !res.isActive }
            : { ...item, checked: !item.isActive }
        )
    );
  };

  return (
    <div className="App">
      {data.map((item) => {
        return <button onClick={() => handleClick(item)}>{item.name}</button>;
      })}
    </div>
  );
}

attached is a code sandbox for debugging: https://codesandbox.io/s/peaceful-sun-20ec0?file=/src/App.js:0-681

I think the main issue is that you are initializing formData to be an empty array. This makes the map call on formData in handleClick do nothing, because calling map on an empty array will not call the map function on any elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM