[英]React not passing state to child via props
我試圖將我的父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)
不顯示新的數據點。
因為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**;
}
檢查此答案以獲取完整的解釋: 為什么setState是異步的。
在加點
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
僅被調用一次,因此您將需要從componentWillReceiveProps
調用composeData
函數,例如
componentWillReceiveProps(nextProps) {
this.composeData(nextProps)
}
componentWillMount() {
this.composeData(this.props.dataPoints)
}
composeData(props){
Object
.keys(props.dataPoints)
.forEach(key => {
** do stuff **
});
return **stuff**;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.