首页 > 解决方案 > 在 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: ''

        }]
}

标签: reactjsformsspread

解决方案


如果您正在使用类组件,请使用setState来更新状态。在这种情况下events是状态的一个字段。所以你可以传播其余的state而不是state.events

  addNewEvent(){
    setState({...this.state, events: [newEvent, ...this.state.events]})
  }

推荐阅读