Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用useState更新数组中对象的值?_Javascript_Arrays_Reactjs_React Hooks_Use State - Fatal编程技术网

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

Javascript 如何使用useState更新数组中对象的值?,javascript,arrays,reactjs,react-hooks,use-state,Javascript,Arrays,Reactjs,React Hooks,Use State,我想使用useState将David和Brian的年龄更新到25岁,但我遇到了一个错误: TypeError:employees.map不是函数 有人能建议我该怎么做吗 import React, { useState, useEffect } from 'react'; function App() { const [employees, setEmployees] = useState([]); useEffect(() => { setEmplo

我想使用
useState
将David和Brian的年龄更新到25岁,但我遇到了一个错误:

TypeError:employees.map不是函数

有人能建议我该怎么做吗

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;
import React,{useState,useffect}来自“React”;
函数App(){
const[employees,setEmployees]=useState([]);
useffect(()=>{
setEmployees([
{姓名:'大卫',年龄:40},
{姓名:'Brian',年龄:35}
]);
}, []);
employees.map((值)=>{
setEmployees({…雇员,年龄:25});
});
console.log(员工)
返回(
这是应用程序组件
);
};
导出默认应用程序;

主要问题是在
setEmployees()
中使用对象
{}
而不是
[]
。该函数只能用于阵列。从文件中:

map()
方法创建一个新数组,其中填充了对调用数组中的每个元素调用所提供函数的结果

如果要将新元素添加到该数组中,应将其用作:

setEmployees(prevState => [
   ...prevState,
   { name: 'New Guy', age: 25 }
]);
要更新所有可以使用的值,请执行以下操作:

setEmployees(prevState => prevState.map(e => ({
   ...e,
   age: 25
});
请参见下面的一个实时示例:

const数据=[
{姓名:'大卫',年龄:40},
{姓名:'Brian',年龄:35}
]
const result=data.map(e=>({…e,年龄:10}))
console.log(结果)