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

标签 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)。 当我添加新评论时,它看起来运行良好,但有一个警告

Warning: Failed propType: Invalid prop comments supplied to CommentList, expected instance of List. Check the render method of CommentBox.

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

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

The messages store could keep track of the users and messages using two lists:

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

It should be pretty straightforward to implement functions to process each payload type. For instance, when the store sees a payload representing a new message, we can just create a new record and append it to the messages list:

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

Note that since the data structures are immutable, we need to assign the result of the push function to this.messages.

最佳答案

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

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

关于javascript - 在 react-js 中使用 immutable-js 时使用 PropTypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32165434/

相关文章:

javascript - Flow 和 Immutable.js 映射

javascript - 加载 HTML 后编译 JS 指令

javascript - 如何将 X 轴标签旋转到条形图中的条形图上?

javascript - 在 javascript 中干燥 html 包装器

javascript - `react-query` 突变 onSuccess 函数没有响应

reactjs - 在 Redux 中重写状态

javascript - 如何将扩展导入 ES6/Typescript 模块

javascript - 反转 Markdown 以进行 bootstrap pagedown 文本区域编辑

javascript - 删除一项后组件列表不更新状态

javascript - 我如何使用 immutable.js 之类的东西在 Redux 中组合多个 combineReducers 函数