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,
},
],
});