如何解决在 React 中使用 Spread 运算符更新状态数组?
我在接受来自 Form 的输入后尝试更新状态数组。状态中已经有带有数据的事件对象,我想从表单中接受数据并附加到现有列表中。我可以执行 newEvents 的控制台日志(来自另一个组件中的表单的数据),但使用扩展运算符无法通过附加它来更新现有状态。
//从另一个组件的表单中获取 newEvent 对象。 // 事件是 具有数据的状态数组 // 打印现有数组 不附加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',Date: ''
}]
}
解决方法
如果您正在使用类组件,请使用 setState
更新状态。在这种情况下,events
是状态的一个字段。所以你可以传播其余的 state
而不是 state.events
。
addNewEvent(){
setState({...this.state,events: [newEvent,...this.state.events]})
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。