简体   繁体   English

使用 React Hooks 修改 react state 属性的最佳方法

[英]The best way to modify react state property with React Hooks

Lets assume I have defined my React state using hooks like that假设我已经使用这样的钩子定义了我的 React state

const items = [{name: 'Jack', age: 1},{name: 'Bill', age: 2},{name: 'Jason', age: 4}];

const [content, setContent] = useState<{name: string, age: number}[]>(items);

What is the best way to modify second element of the array?修改数组的第二个元素的最佳方法是什么?

This is the way how I am doing it at the moment这就是我目前的做法

const newContent = content.map((item,i) => {
if(i == 1){
   return(...item, age: 5)
}
else{
    return item;
}
})
setContent(newContent)

Thanks谢谢

You can use the previous state by giving the setter a function and need to use the correct curly brackets.您可以通过给 setter 一个 function 来使用之前的 state 并且需要使用正确的大括号。

const index = 1; // the index you want to update
const newAge = 5; // the value you want to set

setContent(prev => prev.map((item, i) => {
    if (i === index) {
      return { ...item, age: newAge };
    }
    return item;
  }
);

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

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