我目前遇到让ImmutableJS和React正常工作的问题。这不是使用Redux,因此我在组件中更新状态。
问题是在我更新状态后,我的getter
属性在下一次重新渲染时丢失,导致错误。为什么setState
剥离这些方法?
我没有正确使用ImmutableJS吗? ImmutableJS只适用于Redux吗?
const AssociateRoleLocationStateFactory = RecordFactory<AssociateRoleLocationState>({
isEditing: false
})
export default class IAssociateRoleLocation extends React.Component {
constructor(props) {
super(props)
this.state = new AssociateRoleLocationStateFactory({
isEditing: false
})
// `this.state` has `.get` method to retrieve properties
console.log(`initial state:`, this.state) // Record {_map: Map}
}
toggleEditing() {
let nextState = this.state.set('isEditing', !this.state.get('isEditing'))
// `nextState` has `.get` method to retrieve properties
console.log(`next state:`, nextState) // Record {_map: Map}
this.setState(nextState)
}
render() {
console.log(this.state) // {_map: Map} // Its missing `.get` method on second render
let isEditing = this.state.get('isEditing')
return (
<div className="site-single-column">
{isEditing ? (
<div>
Is Editing!!
</div>
) : (
<button style={{ alignSelf: 'center' }} onClick={this.toggleEditing}>
Toggle
</button>
)}
</div>
)
}
}
答案 0 :(得分:1)
目前,React仅支持普通js对象作为状态。你可以在另一个键/值层中包装你想要的任何东西,比如
constructor(props) {
super(props);
this.state = {
payload: new AssociateRoleLocationStateFactory({
isEditing: false
})
}
}
围绕此进行的讨论如下:https://github.com/facebook/react/issues/3303
但在此之前,保持纯洁。