用于 React 组件状态的 ImmutableJS

ImmutableJS for React Component's state

所以我决定使用 ImmutableJS 来处理 Redux。现在在想用它来管理 React Component 是否方便state。我编码如下:

class Navigation extends React.Component {
  constructor(props) {
    super(props);
    const $$fixedLinks = Immutable.fromJS(this.props.fixedLinks);
    const $$dynamicLinks = Immutable.fromJS(this.props.dynamicLinks);

    this.state = {
      fixedLinks: this.addHrefs($$fixedLinks),
      dynamicLinks: this.addHrefs($$dynamicLinks),
    };
  }

  // Given a list of shape (id, name) we need to
  // add href for the links
  addHrefs = list => list.map(item => item.set('href', toUnderscore(item.get('name'))))

  render() {
    const fixed = this.state.fixedLinks.map(
      link => (
        <Link key={link.get('id')} href={`#${link.get('href')}`} title={link.get('name')} />
      ),
    );
    const dynamic = this.state.dynamicLinks.map(
      link => (
        <Link key={link.get('id')} href={`#${link.get('href')}`} title={link.get('name')} />
      ),
    );
    return (
      <Anchor>
        {fixed}
        {dynamic}
      </Anchor>
    );
  }
}

如您所见,$$ 表示一个不可变对象。但是后来我想用 addHrefs 添加一个新的 属性 并将其保存到 state

它就像一个魅力。但是下面有点尴尬:

<Link key={link.get('id')} href={`#${link.get('href')}`} title={link.get('name')} />

看到了吗?使用 get() 从不可变对象中获取值。

现在,一些问题:

  1. 使用 ImmutableJS 进行管理是个好主意(或方法)吗 状态 React.Component?
  2. 如果我可以为此目的使用 ImmutableJS,那么 this.state 应该是 一个不变的对象?如果是,如何处理this.setState()?
  3. 如果不是这样,我不能使用 loadash 因为它不能与 ImmutableJS,如何处理里面的不可变状态 React.Component?
  1. Is it a good idea (or approach) to use ImmutableJS for managing state in React.Component?

我不明白为什么这会是一个糟糕的想法。它甚至在 React docs.

中被提及
  1. If I can use ImmutableJS for this purpose, should this.state be an immutable object? if so, how to deal with this.setState()?

这真的取决于你。让组件状态不可变是有好处的(比如能够使用 PureComponent 并获得优化的性能)。

我不确定 "deal with this.setState()" 是什么意思。您继续像往常一样使用它:获取您的状态,更新它(从而获得一个新对象),用新对象调用 setState

  1. If not so, I can't use loadash because it won't work with ImmutableJS, how can I deal with immutable states inside React.Component?

您可以调用 const myState = this.state.toJS() 并使用 lodash。只是不要试图改变组件的状态,改变 myState 中的某些东西,因为那是行不通的。

如果我理解正确的话,我希望这能回答你的问题:)