gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:06:14 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com