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

rub*_*yu2 12 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);
}
Run Code Online (Sandbox Code Playgroud)

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

警告:propType失败:无效的prop comments提供给 CommentList,预期的实例List.检查渲染方法 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();
Run Code Online (Sandbox Code Playgroud)

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

this.messages = this.messages.push(new Message({
  timestamp: payload.timestamp,
  sender: payload.sender,
  text: payload.text
});
Run Code Online (Sandbox Code Playgroud)

请注意,由于数据结构是不可变的,我们需要将push函数的结果赋给this.messages.

Mar*_*phy 14

我来到这里寻找一个解决方案,允许一个数组或来自ImmutableJS的任何类型的可迭代对象作为prop传递.如果其他人发现这有用,这就是我想出的:

PropTypes.oneOfType([
  PropTypes.instanceOf(Array),
  PropTypes.instanceOf(Immutable.Iterable)
]).isRequired
Run Code Online (Sandbox Code Playgroud)