简体   繁体   English

如何使用useState更新数组中对象的值?

[英]How to update value in an object in an array using useState?

I want to update David and Brian's age to 25 using useState but I encounter an error:我想使用useState将 David 和 Brian 的年龄更新为 25 岁,但遇到错误:

TypeError: employees.map is not a function.类型错误:employees.map 不是函数。

Can anyone suggest what should I do?谁能建议我该怎么办?

import React, { useState, useEffect } from 'react';

function App() {

    const [employees, setEmployees] = useState([]);

    useEffect(() => {
        setEmployees([
            { name: 'David', age: 40 },
            { name: 'Brian', age: 35 }
        ]);
    }, []);

    employees.map((value) => {
        setEmployees({ ...employees, age: 25 });
    });

    console.log(employees)
    
    return (
        <div>
            This is App component
        </div>
    );
};

export default App;

The main problem is you are using in setEmployees() an object {} instead of an [] .主要问题是您在setEmployees()使用对象{}而不是[] The function .map() can be used only on arrays.函数.map()只能用于数组。 From the documentation:从文档:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. map()方法创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。

If you want to add a new element to that array you should use as:如果要向该数组添加新元素,应将其用作:

setEmployees(prevState => [
   ...prevState,
   { name: 'New Guy', age: 25 }
]);

To update all the values you can use .map() as the following:要更新所有值,您可以使用.map()如下:

setEmployees(prevState => prevState.map(e => ({
   ...e,
   age: 25
});

See a live example below:请参阅下面的示例:

 const data = [ { name: 'David', age: 40 }, { name: 'Brian', age: 35 } ] const result = data.map(e => ({...e, age: 10})) console.log(result)

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

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