【发布时间】:2017-08-22 17:41:18
【问题描述】:
我正在尝试将我的父级 App 状态传递给子组件 Chart。
应用
constructor() {
super();
this.state = {
dataPoints: {
'424353': {
date: '10/10/2016',
qty: '95'
},
'535332': {
date: '10/11/2016',
qty: '98'
},
'3453432': {
date: '10/01/2017',
qty: '94'
}
}
};
this.addPoint = this.addPoint.bind(this);
}
addPoint(dataPoint) {
let dataPoints = {...this.state.dataPoints};
const timestamp = Date.now();
dataPoints[timestamp] = dataPoint;
this.setState({ dataPoints: dataPoints });
console.log('new state', this.state.dataPoints);
}
render() {
return (
<div className="app">
<Chart dataPoints={this.state.dataPoints} />
<FormControl addPoint={this.addPoint} />
</div>
);
}
图表
composeData() {
Object
.keys(this.props.dataPoints)
.forEach(key => {
** do stuff **
});
return **stuff**;
}
componentWillUpdate() {
this.composeData();
}
addPoint 方法有效,即我可以在 React 控制台中看到新数据点已添加到状态中。但它并没有反映在Chart 组件中。 (对我来说)更奇怪的是,当我添加一个点时,addPoint 方法中的 console.log 行(上图):
console.log('new state', this.state.dataPoints)
不显示新数据点。
【问题讨论】:
标签: javascript reactjs components state