在 React 中使用 UseState 更新数组中的所有对象

PYG

我在这里做错了什么?

我从这个开始:

const [notificationList, setNotificationList] = useState([]);

然后填充数组。之后我想更新该数组中的每个对象......但不工作。

setNotificationList(notificationList.map(notif => { ...notif, isRead: true }))

我认为这很明显,但我需要睡觉。

雅库布·科特尔斯

您有语法错误。如果您运行代码,您应该会在控制台中看到它。

// this is the usual "old" syntax
function() {
  return true
}
// this is the es6 arrow function
() => {
  return true
}
// this is the es6 arrow function without braces
() => true

正如您在此处看到的,您可以{}在箭头函数中省略。但是,如果您想返回一个对象,则必须明确,否则引擎无法理解_

// not what you want
() => { key: 'value' }
// what you want
() => ({ key: 'value' })

解决方案:

setNotificationList(notificationList.map(notif => ({ ...notif, isRead: true })))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React useState()-如何更新对象

使用React useState()钩子更新和合并状态对象

有可能在React中使用React.useState(()=> {})吗?

React钩子:如何使用useState()更新嵌套对象上的状态?

React Hooks尝试在数组引用中使用useState

在React useState中使用(或||)语法进行赋值

如何在React Native中使用其索引在useState中更新数组

在React中使用useState更新多个数组对象值

在React中使用useState将对象添加到数组时出现Typescript错误

react中的useState不更新状态对象

React-如何使用useState在对象中推送数组

使用useState在React中更新对象的属性

React useState-如何使用数组设置对象?

在 React 中使用 useState 更新二维数组矩阵

在 React 中使用 useState 未在函数组件中更新状态

useState React 未更新

使用 React useState 更改对象数组

在 React 中使用 useState 映射外部数组后,如何显示/隐藏嵌套数组元素/组件?

如何在 React -TypeScript 中使用 useState 更新、扩展数组?

在 React Native 中使用 useState

更新 React useState 中的对象数组

在 React 中使用 useState 钩子获取对象的初始值

如何使用 React Hook useState 更新 2 个对象

如何使用TypeScript中React useState中的新值更新数组中对象中键的值

React - 如何使用 UseEffect 中的 useState 更新对象数组中的特定字段

使用 useState 更新数组对象

在 React 中使用 useState 挂钩更新对象

比较两个不同的数组并使用 React 中的 useState 更新对象数组

React useState - 将所有对象值更新为 true