我有一个组件(执行文本输入)在另一个组件内呈现两次。
当我点击其中一个文本输入组件中的某个键时,每个组都会收到通知......
该组件采用"14:30"
之类的时间字符串,并且应该允许小时和时间分钟输入。
回流行动:
let TimeActions = Reflux.createActions([
'setHour',
'setMinute'
]);
Reflux mixin:
let TimeMixin = {
init: function() {
this.listenToMany(TimeActions);
},
onSetHour(h) {
this.time.hour = h;
this.trigger(this.time);
},
onSetMinute(m) {
this.time.minute = m;
this.trigger(this.time);
}
};
反应组件:
export default class TimePicker extends React.Component {
constructor(props) {
super(props);
let parts = this.props.time.split(':'),
time = {
hour: parts[0],
minute: parts[1]
};
this.store = Reflux.createStore({
mixins: [ TimeMixin ],
time: time
});
this.state = time;
}
componentDidMount() {
this.unsubscribe = this.store.listen(this.onTimeChanged.bind(this));
}
componentWillUnmount() {
this.unsubscribe();
}
onTimeChanged(time) {
console.log('TIME SET TO', time);
this.setState(time);
}
render() {
let classes = classNames('time-picker');
return (
<div className={classes}>
<table>
<tbody>
<tr>
<td>
<input type="text" className="hour" maxLength="2"
value={this.state.hour}
onChange={this.onHourChanged} />
</td>
<td class="separator">:</td>
<td>
<input type="text" className="minute" maxLength="2"
value={this.state.minute}
onChange={this.onMinuteChanged} />
</td>
</tr>
</tbody>
</table>
</div>
);
}
onHourChanged(event) {
TimeActions.setHour($(this.getDOMNode()).val());
}
onMinuteChanged(event) {
TimeActions.setMinute($(this.getDOMNode()).val());
}
}
我从另一个React组件渲染TimePicker
两次......
...
<TimePicker time={this.props.from} />
<TimePicker time={this.props.to} />
...
...当在任何实例的分钟输入中输入"01"
时,我得到以下日志:
TIME SET TO Object {hour: "08", minute: "01"}
TIME SET TO Object {hour: "12", minute: "01"}
知道我做错了什么?
答案 0 :(得分:1)
这是因为您在组件的构造函数级别创建了两个存储。
您应该在组件外部创建商店,因此只要您有一个或数百个组件实例,就只有一个商店存在。