我读完了这行 here
this.setState({ chats: [...this.state.chats, data], test: '' });
我认为我们在状态中保存聊天数组,...this.state.chat 指的是原始聊天变量,然后我迷路了
最佳答案
代码更新了两个状态属性:
chats
- 使用 array spread 从之前的chats
和新的data
创建一个新数组.test
- 将测试更新为空字符串。这是原始代码中的错字,应该是text
。
传播示例:
const chats = [1, 2, 3];
const data = 4;
const newChats = [...chats, data];
console.log(newChats);
但是,由于状态是异步的,最好使用 updater callback更新状态,因为:
Both prevState and props received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with prevState.
更新示例:
this.setState((prevState) => ({ chats: [...prevState.chats, data], test: '' }));
关于javascript - react : Can someone please elaborate this line to me,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084057/