在react-js中的immutable-js时使用PropTypes

时间:2015-08-23 10:02:55

标签: javascript reactjs immutable.js

我在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失败:提供的无效道具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的结果。

2 个答案:

答案 0 :(得分:13)

我来到这里寻找一种解决方案,允许将来自ImmutableJS的数组或任何类型的可迭代对象作为prop传递。如果其他人发现这有用,请按照我的意见:

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

答案 1 :(得分:0)

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

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.'
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>