我在 React 中有一个名为“App”的父组件,它使用 HighCharts 实现呈现一个“Calories”子组件。
我期望的是根据 React 生命周期,父组件渲染子组件,然后调用 componentDidMount()。然后,我使用 fetch 来异步获取数据,完成后 setState 是带有用户对象的父级。然后它将使用 user={this.state.user} 重新渲染子组件,并且它将在子组件中可用。但是当我在孩子的 componentWillReceiveProps 中记录 this.props 时,用户对象不存在。因此子组件中的这一行记录“未定义”:
componentWillReceiveProps: function(){
const series = this.props.series;
console.log("component Will Receive Props")
console.log(this.props);
}
这是我的完整代码:
const App = React.createClass({
//parent component to render all elements and hold state
getInitialState(){
return{
user: {},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
};
},
componentDidMount: function(){
const fb_id = location.pathname.replace("/users/","");
fetch("https://someurl.com/usersdata/" + fb_id)
.then(rsp => rsp.json())
.then(json => {
if(json.error && json.error.message){
throw new Error(json.error.message);
}
this.setState({user:json}, ()=>{
console.log("state updated");
console.log(this.state);
});
});
},
render: function(){
return (
<div className="container">
<div clasNames="row">
<div className="col-xs-12">
{/*Send this.state.user data from fetch to child component*/}
<Calories series={this.state.series} user={this.state.user}/>
</div>
</div>
<div className="row">
<div className="col-xs-7">
<div className="bottom-left" id="weight-line-chart">
<Weight/>
</div>
</div>
<div className="col-xs-5">
<div className="bottom-right" id="avg-calories-pie-chart">
<AverageCal/>
</div>
</div>
</div>
</div>
);
}
});
//Calories Line chart
const Calories = React.createClass({
componentDidMount: function(){
const series = this.props.series;
console.log("component Did Mount");
console.log(this.props);
$(function () {
const myChart = Highcharts.chart('calories-line-chart', {
chart: {
type: 'line'
},
title: {
text: 'Your Calories Over Time'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: series
});
});
},
componentWillReceiveProps: function(){
const series = this.props.series;
console.log("component Will Receive Props")
console.log(this.props);
$(function () {
const myChart = Highcharts.chart('calories-line-chart', {
chart: {
type: 'line'
},
title: {
text: 'Your Calories Over Time'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: series
});
});
},
render:function(){
return(
<div>
<h3>Calories Intake</h3>
<div className="top" id="calories-line-chart">
</div>
</div>
);
}
});
任何人都可以帮助我我做错了什么?