javascript - react : Can someone please elaborate this line to me

标签 javascript reactjs

我读完了这行 here

this.setState({ chats: [...this.state.chats, data], test: '' });

我认为我们在状态中保存聊天数组,...this.state.chat 指的是原始聊天变量,然后我迷路了

最佳答案

代码更新了两个状态属性:

  1. chats - 使用 array spread 从之前的 chats 和新的 data 创建一个新数组.
  2. 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/

相关文章:

javascript - Wordpress 在 ajax 请求回调中获取当前页面名称或 ID

javascript - 将 jQuery 数据附加为字符串时在 div 上设置它

javascript - 我的 React 应用程序的根文件夹与 React-Router 冲突

javascript - 为什么 Vue 在替换或创建和删除数组项时使用不同的动画?

javascript - Google 脚本数字格式错误

javascript - 多个链接的 dc.js 图表的 d3-tooltips

reactjs - 我的数据测试 ID 在那里,但我的测试找不到它 react enzyme Jest 单元测试

javascript - react .js : handleSubmit or onClick not triggered when rendered on the server side

reactjs - 用户单击弹出窗口中的按钮后关闭弹出窗口 react-leaflet

reactjs - 更改 react 选择中选定的值组件