简体   繁体   English

ReactJS:如何更新数组 state 中的数据

[英]ReactJS: How to update the data in array state

    const [rowData, setRowData] = useState([]);
    const old = {id: 'stud1', name: 'jake', room: '2'};
    const newData = {name: 'jake', room: '3A'};

    useEffect(() => {
        let ignore = false;
        (async function getUsers() {
          let response = await getAll({ length: 999 });
          if (!ignore) setRowData(response['data']['data']);
        })()
        return () => {
          ignore = true;
        }
      }, []);

    (async function updateItem() {
              await update(oldData.id, newData).then(response => {
//value of response['data'] = {id: 'stud1', name: 'jake', room: '3A'}
                setRowData(arr => [...arr, response['data']]);
              }).catch(err => {
                console.log(err);
              })
            })()

How to update the array list without appending a new data.如何在不附加新数据的情况下更新数组列表。 cause I tried this setRowData(arr => [...arr, response['data']]);因为我试过这个setRowData(arr => [...arr, response['data']]); then it keeps appending a data.然后它继续附加数据。

Instead it will update the value in the array it will append on it.相反,它将更新数组中的值,它将 append 放在上面。

Since you want to update one item within the state array, you can use map and update the item based on the id like below由于您想更新 state 数组中的一项,您可以使用 map 并根据下面的 id 更新该项

  (async function updateItem() {
      await update(oldData.id, newData).then(response => {
        setRowData(arr => arr.map(item => {
                if (item.id === response.data.id) {
                     return response.data;
                }
                return item;
         });
      }).catch(err => {
        console.log(err);
      })
    })()

I do not think you need a spread operator.. you can just use array.map().. maybe something like this will help you..我不认为你需要一个传播运算符..你可以使用 array.map()..也许这样的东西会帮助你..

const old = [{id: 'stud1', name: 'jake', room: '2'},{id: 'stud2', name: 'jack', room: '2'}];
const newData = {id: 'stud1', name: 'jakey', room: '3A'};

const x = old.map((stud) => {
  if(stud.id === newData.id){
    stud = newData;
  }
  return stud;
});
console.log(x);

then you can use the x for setRowData(x)那么您可以将 x 用于 setRowData(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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