在 React 中使用 Spread 运算符更新状态数组?

Updating state array using Spread operator in React?

我正在尝试在接受来自表单的输入后更新状态数组。 State 中已经有带有数据的事件对象,我想从表单中接受数据并附加到现有列表中。我能够执行 newEvents 的控制台日志(来自另一个组件中的表单的数据),但是使用展开运算符无法通过附加它来更新现有状态。

//getting newEvent object from form in another component. // events is an array in state which has data //priniting the existing array without appending newEvent //printing data from form (newEvent) properly

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: ''

        }]
}

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

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