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

这是我的状态对象

/*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);
}

}

我能够接收数据,但不知道如何将其存储在状态对象中.

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

用于下一帧

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"}]} 

AS YOU CAN SEE THIS LAST RESPONSE IS SET TO FIRST INDEX(I AM USING CLASS BASED COMPONENTS IN REACT NO HOOKS)

100

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

enter image description here

推荐答案

调用setState的方式没有所需的格式(即将更新的状态部分)

以下任何一种方法都可以

Directly set the piece of the state object

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

Using the callback function of setState method

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

Reactjs相关问答推荐

如何使用mui为可重复使用的react 按钮应用不同的风格

根据另一个Select中的选定值更改Select中的值

将对象添加到集合中的数组时的no_id字段

App.js中的H2组件不会动态呈现.这可能是什么问题?

生成Reaction Vite应用程序的停靠容器时无法识别环境变量

在transformResponse中使用来自其他查询的缓存

为什么我得不到我想要的数据?

点击页脚链接时,如何更改ReactJS导航栏中的活动菜单项(样式为Tailwind CSS)?

在任何渲染之前在ReactJs中获取数据

定位数组中的一项(React、useState)

如何根据ReactJS中元素列表中的布尔值仅显示一次值

如何根据用户在react.js中的 Select , Select 多个心形图标?

根据其中的值不同地react setState 更新状态

图像路径很奇怪,部署 Next.js 应用程序后我看不到任何图像

@react-three/postprocessing 没有匹配的从 three.module.js 导出以导入WebGLMultisampleRenderTarget

Github 页面无法正确呈现 CSS,因为它是本地的

更新 Next.js 路由查询更改的状态会导致无限循环

添加 React/Redux 组件模板的 VS Code 扩展

Context Api React 的问题

在渲染不显示子元素之后,再次渲染时,子元素状态数据完全消失了.为什么会这样以及如何防止它发生?