我正在尝试将我的父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
组件中。更奇怪的是(对我而言)当我添加一个点时,console.log
方法中的addPoint
行(上图):
console.log('new state', this.state.dataPoints)
不显示新数据点。
答案 0 :(得分:1)
由于setState
为asynchronous
,因此请使用此链接查看更新后的值:
this.setState({ dataPoints: dataPoints }, () => {
console.log('new state', this.state.dataPoints);
});
第二件事是,每当props
值发生任何变化时,都会调用componentWillReceiveProps
生命周期方法,一旦添加新项目,就在此方法中进行计算。像这样:
componentWillReceiveProps(newProps) {
console.log('update props values', newProps);
Object
.keys(newProps.dataPoints)
.forEach(key => {
** do stuff **
});
return **stuff**;
}
检查此答案以获取完整说明:why setState is asynchronous.
答案 1 :(得分:1)
添加点
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);
}
在上面的代码中,您没有看到更新的值,因为setState需要时间进行变异,您必须在setState回调中记录它
this.setState({ dataPoints: dataPoints }, function(){
console.log('new state', this.state.dataPoints);
});
在Chart组件中,如果你在其中使用this.props
,你需要绑定composeData函数
composeData = () =>{
Object
.keys(this.props.dataPoints)
.forEach(key => {
** do stuff **
});
return **stuff**;
}
但componentWillMount
只调用一次,因此您需要从composeData
调用componentWillReceiveProps
函数,例如
componentWillReceiveProps(nextProps) {
this.composeData(nextProps)
}
componentWillMount() {
this.composeData(this.props.dataPoints)
}
composeData(props){
Object
.keys(props.dataPoints)
.forEach(key => {
** do stuff **
});
return **stuff**;
}