在过去的几周里,我一直在使用facebooks框架React.js和Backbone一起工作.当Backbone集合发生变化时,我仍然不能完全确定重新渲染React组件的最佳方法是什么已作为道具传入.
目前我所做的是在componenentWillMount集合上设置change/add/remove监听器并在触发时设置状态:
componentWillMount: function(){
var myCollection = this.props.myCollection;
var updateState = function(){
this.setState({myCollection: myCollection.models});
}
myCollections.on("add remove", updateState, this);
updateState();
}
render: function(){
var listItems = this.state.myCollection.map(function(item){
return <li>{item.get("someAttr")}</li>;
});
return <ul>{listItems}</ul>;
}
Run Code Online (Sandbox Code Playgroud)
我已经看到了将模型克隆到状态的示例:
var updateState = function () {
this.setState({ myCollection: _.clone(this.myCollection.models) });
};
Run Code Online (Sandbox Code Playgroud)
我也看到过变体,其中props中的模型/集合直接用于渲染而不是使用状态,然后在集合/模型更改时调用forceUpdate,导致组件重新渲染
componentWillMount: function(){
var myCollection = this.props.myCollection;
myCollections.on("add remove", this.forceUpdate, this);
}
render: function(){
var listItems = this.props.myCollection.map(function(item){
return <li>{item.get("someAttr")}</li>;
});
return <ul>{listItems}</ul>;
}
Run Code Online (Sandbox Code Playgroud)
不同的方法有哪些好处和缺点?有没有办法做到这就是The React方式?