reactjs - 使用 ImmutableJS 对象作为 React 组件状态

标签 reactjs immutability setstate

我正在尝试使用 ImmutableJS 来帮助维护 React 组件中的状态。如果状态包含一个不可变的对象,我可以很好地使用它。但是,如果整个状态是一个不可变的对象,那么每当我尝试setState()时它就会失败,并出现错误,提示

TypeError: this.state.get is not a function.

下面是重现错误的最小示例。每次按下递增按钮时,计数变量都应该递增并重新渲染。请帮助我理解为什么这种方法不起作用。谢谢!

import React from 'react';
import { Map as ImmutableMap } from 'immutable'

class App extends React.Component {

  constructor (props) {
    super(props)
    this.state = ImmutableMap({ count: 0 }) // entire state is immutable
  }

  increment () {
    const newCount = this.state.get('count') + 1
    this.setState(prevState => prevState.set('count', newCount))
  }

  render() {
    return (
      <div>
        { this.state.get('count') } // produces error after setState()
        <button onClick={this.increment.bind(this)}>Increment</button>
      </div>
    );
  }

}

export default App;

最佳答案

参见this part文档。

When you call setState(), React merges the object you provide into the current state.

因此,在 setState 之后,您将留下一个空对象。

来自Immutable.js documentation :

Note that state must be a plain JS object, and not an Immutable collection, because React's setState API expects an object literal and will merge it (Object.assign) with the previous state.

在当前版本的代码中,状态的实际合并发生在ReactUpdateQueue.js中。在 getStateFromUpdate 函数中使用以下行:

  // Merge the partial state and the previous state.
  return Object.assign({}, prevState, partialState);

关于reactjs - 使用 ImmutableJS 对象作为 React 组件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53991562/

相关文章:

javascript - 使用 "onClick={}"被认为是一种不好的做法吗?

javascript - React Dragula 给出 "Failed to compile"和 "unexpected"错误

java - 不变性和图形模型——如何创建它们?

javascript - 单击一行获取该特定行的数据

Flutter setState 预期有 3 个位置参数,但发现 1 个错误

reactjs - react native typescript 屏幕测试返回测试套件运行失败。错误 react-native-permissions : NativeModule. RNPermissions 为空

hibernate - 使用Hibernate将可变转换为不可变

使用rust "error: moving out of immutable field"

javascript - setState() 函数不起作用,我无法更新我的状态。我怎么解决这个问题?

javascript - 现有应用程序上的 React Native 电影教程的图像未在设备上显示