在过去的几周里,我一直在使用 facebooks 框架 React.js 和 Backbone,但我仍然不完全确定当已作为 Prop 传入的主干集合。
目前我所做的是在 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>;
}
我见过将模型克隆到状态的示例:
var updateState = function () {
this.setState({ myCollection: _.clone(this.myCollection.models) });
};
我也见过一些变体,在render中直接使用props中的model/collection,而不是使用state,然后在collections/model发生变化时调用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>;
}
不同的方法有哪些优点和缺点? 有没有一种React 方式 可以做到这一点?
最佳答案
您可以使用基于此 BackboneMixin 的 mixin 来帮助自动绑定(bind)和取消绑定(bind)监听器,而不是手动绑定(bind)事件监听器:
https://github.com/facebook/react/blob/1be9a9e/examples/todomvc-backbone/js/app.js#L148-L171
然后你只需写
var List = React.createClass({
mixins: [BackboneMixin],
getBackboneModels: function() {
return [this.props.myCollection];
},
render: function(){
var listItems = this.props.myCollection.map(function(item){
return <li>{item.get("someAttr")}</li>;
});
return <ul>{listItems}</ul>;
}
});
当集合中发生任何变化时,组件将被重新渲染。您只需将 BackboneMixin 放在顶层组件上——任何后代都将同时自动重新渲染。
关于javascript - 处理 react.js 中的主干模型/集合更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20371566/