使用 ImmutableJS 对象作为 React 组件状态
Using an ImmutableJS Object as the React Component State
我正在尝试使用 ImmutableJS 来帮助维护 React 组件中的状态。如果状态 包含 一个不可变对象,我就可以很好地使用它。但是,如果 entire 状态是一个不可变对象,那么每当我尝试 setState() 时它都会失败,并显示
TypeError: this.state.get is not a function.
下面是重现错误的最小示例。每次按下 increment 按钮时,count 变量应该递增并重新呈现。请帮助我理解为什么这种方法不起作用。谢谢!
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
之后你将得到一个空对象。
这是另一个相关资源:https://github.com/facebook/immutable-js/wiki/Immutable-as-React-state
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);
我正在尝试使用 ImmutableJS 来帮助维护 React 组件中的状态。如果状态 包含 一个不可变对象,我就可以很好地使用它。但是,如果 entire 状态是一个不可变对象,那么每当我尝试 setState() 时它都会失败,并显示
TypeError: this.state.get is not a function.
下面是重现错误的最小示例。每次按下 increment 按钮时,count 变量应该递增并重新呈现。请帮助我理解为什么这种方法不起作用。谢谢!
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
之后你将得到一个空对象。
这是另一个相关资源:https://github.com/facebook/immutable-js/wiki/Immutable-as-React-state
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);