javascript - 添加功能的笨拙实现

标签 javascript reactjs ecmascript-6

我很难理解这是为什么:

addItem = item => {
    this.setState({ grudges: [grudge, ...this.state.grudges] });
}

存在相当笨拙的实现。不会

this.state.grudges.push(grudge)

够了吗?

最佳答案

这还不够,因为 React state is expected to be immutable :

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

这个“笨拙的实现”也是不正确的,this.state 不应与 this.setState 一起使用,因为 setState is asynchronous并可能导致竞争条件:

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

<...>

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

正确的方法是使用updater函数:

addItem = item => {
    this.setState(({ grudges }) => ({ grudges: [grudge, ...grudges] }));
}

它还受益于解构语法。

关于javascript - 添加功能的笨拙实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53685630/

相关文章:

javascript - 如何在现有的浏览器选项卡中打开网址?

javascript - 展平嵌套对象而不出现 TS 错误

javascript - Nashorn错误: java. lang.NoSuchMethodException:没有这样的函数renderServer

javascript - 如何在 react 中获取对象中的嵌套数组?

javascript - 基于配置的Webpack多重 bundle

javascript - 如何在 AngularJS 中将 Modal 的响应作为服务处理

javascript - 使用 jQuery 缩放后检索背景图像的大小?

javascript - Props 是 React with Typescript 中已弃用的符号

javascript - 如何从 Redux 存储获取状态

javascript - 使用 array.prototype 时如何访问数组