使用ImmutableJS和React setState

问题描述 投票:0回答:1

我目前遇到让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>
    )
  }
}
reactjs immutable.js setstate
1个回答
1
投票

目前,React仅支持普通js对象作为状态。您可以在另一个键/值层中包装您想要的任何内容

constructor(props) {
  super(props);
  this.state = {
    payload: new AssociateRoleLocationStateFactory({
      isEditing: false
    })
  }
}

有关这方面的讨论如下:https://github.com/facebook/react/issues/3303

但在此之前,保持纯洁。

© www.soinside.com 2019 - 2024. All rights reserved.