reactjs - 在 React 中使用 Spread 运算符更新状态数组?
问题描述
我在接受来自 Form 的输入后尝试更新状态数组。State 中已经有带有数据的事件对象,我想从表单中接受数据并附加到现有列表中。我能够对 newEvents(来自另一个组件中的表单的数据)进行控制台日志,但是使用扩展运算符无法通过附加来更新现有状态。
// 从另一个组件的表单中获取 newEvent 对象。// events 是一个状态数组,其中包含数据 // 打印现有数组而不附加 newEvent // 正确打印来自表单 (newEvent) 的数据
testmethodfornow = (newEvent) => (
{ ...this.state.events, events: [newEvent, ...this.state.events] },
console.log(this.state.events),
console.log(newEvent)
)
我希望将 newEvent 添加到事件中:(有人可以帮忙吗?
新事件结构:
const newEvent = { IdText: uuid(), EventName, Venue, Time };
状态中的事件数组结构:
state = {
flag: false,
title: "State Check",
events: [
{
IdText: '1',
EventName: 'New Year Party 2022',
Venue: 'The Social',
Time: '8:00 PM- 1:00AM',
Date: ''
},
{
IdText: '2',
EventName: 'StandUp Comedy',
Venue: 'ShilpaRamam',
Time: '8:00 PM- 1:00AM',
Date: ''
}]
}
解决方案
如果您正在使用类组件,请使用setState
来更新状态。在这种情况下events
是状态的一个字段。所以你可以传播其余的state
而不是state.events
。
addNewEvent(){
setState({...this.state, events: [newEvent, ...this.state.events]})
}
推荐阅读
- node.js - 由于重定向到 HTTPS,Docker Express.js 不提供静态文件(Fastify 也是一个问题)
- django - 代理完成任务执行后,如何让 Django-Q 发送消息?
- c++ - 如何从 Qt 中的 MainWindow 继承?
- mysql - MYSQL 中的 ANY 和 SOME 有什么区别吗?
- shell - Gitlab CI:如何从脚本传递错误消息
- python - 如何从 plt 图中删除曲线?
- flutter-test - 如何在命令行上查看所有 Flutter 测试的结果,而不仅仅是摘要?
- php - 未定义索引:post(wordpress 插件)
- python - Windows 10 64 上的 Anaconda 2020.02,导航器出现问题
- android - 访问第三方库的活动视图并更改文本