Javascript 如何使用多个根组件保持数据分离?
我正在使用React.js构建我的整个网站,如下所示:Javascript 如何使用多个根组件保持数据分离?,javascript,reactjs,reactive-programming,react-component,Javascript,Reactjs,Reactive Programming,React Component,我正在使用React.js构建我的整个网站,如下所示: React.render( <div id="mainWrapper"> <MainHeader /> <div id="contentWrapper" className="contentWrapper"> <MainFlow data={example_data} /> <AddE
React.render(
<div id="mainWrapper">
<MainHeader />
<div id="contentWrapper" className="contentWrapper">
<MainFlow data={example_data} />
<AddElementWrapper data={activities} />
</div>
</div>,
document.body
);
首先:我认为只有当我想要操作的组件有另一个所有者时,这才是一个问题。但是,我的组件没有作为所有者的React组件,只有作为父级的HTML元素
我可以通过将所有应用程序数据附加到单个根组件来避免这个问题。但是,我希望将某些数据集分开。有办法吗?您可以将道具复制到子组件的状态,然后更改状态 在MainFlow和AddElementWrapper组件中,您可以使用:
getInitialState: function() {
return {activities: this.props.data};
},
然后,您可以使用this.state.activities并使用setState({activities:yourObject})修改它。您应该定义一个包装器组件,并在那里维护数据的状态,当外部世界的数据发生更改时,只需调用setState即可
Wrapper = React.createClass({
getInitialState: function() {
return {example_data: example_data, activities: activities};
},
refresh: function() {
this.setState({example_data: this.state.example_data, activities: this.state.activities});
},
render: function() {
return (
<div id="mainWrapper">
<MainHeader/>
<div id="contentWrapper" className="contentWrapper">
<MainFlow data={this.state.example_data} />
<AddElementWrapper data={this.state.activities} />
</div>
</div>
);
}
});
React.render(<Wrapper/>);
Wrapper=React.createClass({
getInitialState:函数(){
返回{example_data:example_data,activities:activities};
},
刷新:函数(){
this.setState({example_数据:this.state.example_数据,活动:this.state.activities});
},
render:function(){
返回(
);
}
});
React.render();
我们的想法是让React组件显式地监听数据更改。为此,您将在组件装载时设置回调
我建议寻找两种情况:主干+反应(以及BackboneReact混合)或通量+反应
flux方法是拥有一个关于数据可用性的全局事件系统(dispatcher),主干方法是注册到特定的收集事件
此代码直接来自TodoMVC React主干网项目的BackboneMixin:
componentDidMount: function() {
// Whenever there may be a change in the Backbone data, trigger a
// reconcile.
this.getBackboneCollections().forEach(function(collection) {
// explicitly bind `null` to `forceUpdate`, as it demands a callback and
// React validates that it's a function. `collection` events passes
// additional arguments that are not functions
collection.on('add remove change', this.forceUpdate.bind(this, null));
}, this);
},
更多:
- 主干+反应示例
componentDidMount: function() {
// Whenever there may be a change in the Backbone data, trigger a
// reconcile.
this.getBackboneCollections().forEach(function(collection) {
// explicitly bind `null` to `forceUpdate`, as it demands a callback and
// React validates that it's a function. `collection` events passes
// additional arguments that are not functions
collection.on('add remove change', this.forceUpdate.bind(this, null));
}, this);
},