【问题标题】:Using PropTypes when immutable-js in react-js在 react-js 中使用 immutable-js 时使用 PropTypes
【发布时间】:2015-11-16 21:08:41
【问题描述】:

我在 React 中使用 immutable-js 和 react-immutable-proptypes。

// CommentBox.jsx
getInitialState() {
    return {
        comments: Immutable.List.of(
            {author: 'Pete Hunt', text: 'Hey there!'},
            {author: 'Justin Gordon', text: 'Aloha from @railsonmaui'}
        )
    };
},
render(){
    console.log(this.state.comments.constructor);
    return (
      <div className='commentBox container'>
        <h1>Comments</h1>
        <CommentForm url={this.props.url} />
        <CommentList comments={this.state.comments} />
      </div>
    );
}


// CommentList.jsx
propTypes: {
    comments: React.PropTypes.instanceOf(Immutable.List),
},

// CommentStore.js
handleAddComment(comment) {
    this.comments.push(comment);
}

页面初始化时,没有问题,一切正常,没有警告。 控制台日志显示commentsfunction List(value)。 当我添加新评论时,它看起来运行良好,但有一个警告

警告:失败的 propType:无效的 prop comments 提供给 CommentListList 的预期实例。检查渲染方法 CommentBox.

控制台日志显示commentsfunction Array()。 那么,为什么comments 构造函数会从List 变为Array

而且我已经阅读了http://facebook.github.io/react/docs/advanced-performance.html#immutable-js-and-flux

消息存储可以使用以下方式跟踪用户和消息 两个列表:

this.users = Immutable.List();
this.messages = Immutable.List();

实现要处理的函数应该非常简单 每个有效载荷类型。例如,当商店看到有效载荷时 代表一条新消息,我们可以创建一条新记录并追加 将其添加到消息列表中:

this.messages = this.messages.push(new Message({
  timestamp: payload.timestamp,
  sender: payload.sender,
  text: payload.text
});

注意,由于数据结构是不可变的,我们需要分配 推送函数的结果到 this.messages。

【问题讨论】:

  • this.comments.push(comment) 表达式返回一个新列表,但不会修改该列表(根据定义,因为它是不可变的)
  • 我是从facebook.github.io/react/docs/…那里学到的。
  • 在那篇文章中,他们将调用结果分配给属性本身。
  • "请注意,由于数据结构是不可变的,我们需要将 push 函数的结果分配给 this.messages。"请再看一遍那篇文章。
  • 谢谢。我想我误解了不可变的。

标签: javascript reactjs immutable.js


【解决方案1】:

我来这里是为了找到一个解决方案,该解决方案允许将数组或来自 ImmutableJS 的任何类型的可迭代对象作为道具传递。如果其他人觉得这很有用,这就是我想出的:

PropTypes.oneOfType([
  PropTypes.instanceOf(Array),
  PropTypes.instanceOf(Immutable.Iterable)
]).isRequired

【讨论】:

    【解决方案2】:

    您可以指定自定义验证器。

    propName: function(props, propName, componentName) {
      if (!List.isList(props[propName]) && !Array.isArray(props[propName])) {
        return new Error(
          'Invalid prop `' + propName + '` supplied to' +
          ' `' + componentName + '`. Validation failed.'
        );
      }
    }
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 1970-01-01
      • 2019-03-19
      • 2016-10-06
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 2020-10-12
      • 2018-09-28
      相关资源
      最近更新 更多