我试图每次在第一个索引上设置状态数据以在对象数组中做出反应

I am trying to set data in state everytime on first index for react in array of object

state = {
    resposne: [{ id: null, sentMessage: "", receviedMessage: "" }],
  };

这是我的状态对象 我正在从 API:

中获取数据
/*CONSIDER ABOVE API CALL IS WORKING AS I AM RECEIVING DATA ALREADY*/
.then((response) => {
        return response.json();
      })
      .then((data) => {
if (data) {
this.setState(
            this.state.response.push({
              id: data.id,
              receivedMessage: data.choices[0].text,
              sentMessage: message,
            })
          );
          console.log(this.state);
}

}

我能够接收数据,但不知道如何将其存储在状态对象中。 我的最终状态对象应该是这样的: API 回应

id:1a,
sentMessage:"hello",
receviedMessage:"Hey,How are you"
/*state should be*/
state={
response:[{id:"1a",sentMessage:"hello",receviedMessage:"Hey,How are you"}]}

下一帧 API 回应

id:1b,
sentMessage:"new message",
receviedMessage:"this is new message"
/*state should be*/
state={
response:[{id:1b,sentMessage:"new message",receviedMessage:"this is new message"},{id:"1a",sentMessage:"hello",receviedMessage:"Hey,How are you"}]} 

如您所见,最后的响应设置为第一个索引(我在没有钩子的反应中使用 CLASS 基于组件)

控制台输出 [0:{id:NULL,sentMessage:"",receivedMessage:""},1:{id:1b,sentMessage:"新消息",receviedMessage:"这是新消息"},{id:"1a", sentMessage:"hello",receviedMessage:"Hey, How are you"},response:[...]] 这是控制台的输出:使用以下解决方案

this.setState({
            response: [
              ...this.state.resposne,
              {
                id: data.id,
                receivedMessage: data.choices[0].text,
                sentMessage: message,
              },
            ],
          });

您调用 setState 的方式没有要求的格式(要更新的状态部分)

以下两种方式都行

直接设置状态对象的那一块

this.setState({
  response: [
    ...this.state.response,
    {
      id: data.id,
      receivedMessage: data.choices[0].text,
      sentMessage: message
    }
  ]
});

使用setState方法的回调函数

this.setState((prevState) => ({
  ...prevState,
  response: [
    ...prevState.response,
    {
      id: data.id,
      receivedMessage: data.choices[0].text,
      sentMessage: message
    }
  ]
}));