我正在尝试使用 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/