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)
当页面初始化时,没问题,一切正常,没有警告.控制台日志显示comments
是function List(value)
.当我添加新评论时,它看起来效果很好,但是有一个警告
警告:propType失败:无效的prop
comments
提供给CommentList
,预期的实例List
.检查渲染方法CommentBox
.
并且控制台日志显示comments
是function Array()
.那么,为什么comments
构造函数会List
变为Array
?
我已阅读http://facebook.github.io/react/docs/advanced-performance.html#immutable-js-and-flux.
消息存储可以使用两个列表跟踪用户和消息:
Run Code Online (Sandbox Code Playgroud)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 });
请注意,由于数据结构是不可变的,我们需要将push函数的结果赋给this.messages.
Mar*_*phy 14
我来到这里寻找一个解决方案,允许一个数组或来自ImmutableJS的任何类型的可迭代对象作为prop传递.如果其他人发现这有用,这就是我想出的:
PropTypes.oneOfType([
PropTypes.instanceOf(Array),
PropTypes.instanceOf(Immutable.Iterable)
]).isRequired
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8558 次 |
最近记录: |