【发布时间】:2016-06-02 01:29:13
【问题描述】:
我有 2 个组件。一个项目容器和一个项目设置面板(以后会有更多项目设置面板)。
我在面板中有一个开关,调用“switchSubmit”函数来更新状态,然后调用“handleSubmit”函数,该函数包含一个根据 Switch Button 的值更新 Flux Store 的操作,我正在设置状态,但是它似乎总是在调用我的操作时选择的先前值。
我读到 setState 不是同步的,我也看过一些示例,但不知道如何应用正确的调用和函数来设置状态,并在调用此特定操作时准备好更新的状态以供使用我正在编写的代码。
这是我的代码:
var React = require('react/addons');
var Actions = require('../../Actions');
var ConfigurationStore = require('../../stores/Configuration');
var Controller = React.createClass({
getInitialState: function () {
ConfigurationStore.reset();
Actions.getConfigurationSettings();
return this.getStateFromStores();
},
getStateFromStores: function () {
return {
configuration: ConfigurationStore.getState()
};
},
componentDidMount: function () {
ConfigurationStore.addChangeListener(this.onStoreChange);
},
componentWillUnmount: function () {
ConfigurationStore.removeChangeListener(this.onStoreChange);
},
onStoreChange: function () {
this.setState(this.getStateFromStores());
},
render: function () {
return (
<section className="section-settings container">
<h1 className="page-header">Projects</h1>
<div className="row">
<div className="col-sm-12">
<div className="row">
<div className="col-sm-3">
</div>
<div className="col-sm-9">
<h2>Project Settings</h2>
<hr />
<ProjectContainer data={this.state.configuration} />
</div>
</div>
</div>
</div>
</section>
);
}
});
var ProjectContainer = React.createClass({
getInitialState: function () {
return {
active: false
};
},
componentWillReceiveProps: function (nextProps) {
this.setState({
active: nextProps.data.active
});
},
render: function () {
return (
<div>
<ProjectPanel data={this.props.data}></ProjectPanel>
</div>
);
}
});
var ProjectPanel = React.createClass({
getInitialState: function () {
return {
active: false
};
},
componentWillReceiveProps: function (nextProps) {
this.setState({
active: nextProps.data.active
});
},
handleSubmit: function () {
Actions.updateConfigurationSettings({
active: this.state.active
});
},
switchSubmit: function(event) {
event.stopPropagation();
this.setState({
active: event.currentTarget.checked
});
this.handleSubmit();
},
render: function() {
var formElements = (
<fieldset>
<SwitchButton
name="switch-1"
onChange={this.switchSubmit}
checked={this.props.active}
/>
</fieldset>
);
}
return (
<div className="project-holder">
<div className="project-config">
<form onSubmit={this.handleSubmit}>
{formElements}
</form>
</div>
</div>
);
}
});
任何帮助将不胜感激!
【问题讨论】:
标签: javascript reactjs flux reactjs-flux