当父项和axios.get请求中的道具发生更改时,我想将更新后的状态传递给子组件,状态从服务器获取数据。我在子级中拥有第一个状态,但是在更改道具后,父级状态得到了更新,但是更新后的状态无法传递给子级组件。
ParentComponent
export default class OverallProgress extends Component {
constructor(props) {
super(props);
this.state = {
selectedCourseID: props.selectedCourseID,
overallProgressData: null,
blocking: true
};
}
componentDidMount() {
this._loadData(this.props.selectedCourseID);
}
componentWillReceiveProps(nextProps) {
this.setState({selectedCourseID: nextProps.selectedCourseID});
}
componentDidUpdate(prevProps) {
if (this.props.selectedCourseID !== prevProps.selectedCourseID) {
this._loadData(this.props.selectedCourseID);
}
}
_loadData(selectedCourseID) {
axios.get('/userquery/getDataForWidgets?widget_id=' + this.props.widgetID + '&course_id=' + selectedCourseID)
.then((response) => {
this.setState({
overallProgressData: response.data,
chartReportView: true,
blocking: false
});
})
.catch((error) => {
alert('Oops! Something went wrong. Please refresh the page and try again.');
if (error.response) {
console.log(error.response);
}
});
} render(){
return(
<div>
<OverallProgressLineChart
data={this.state.overallProgressData}
selectedCourseID={this.state.selectedCourseID}
/>
</div>)}
子组件
export default class OverallProgressLineChart extends Component {
constructor(props) {
super(props);
this.state = {
courseWiseScoreDetailsOfAllExams: props.data,
dataForSelectedCourse: {
courseID: null,
courseName: null,
examNames: [],
examScorePercentages: [],
highestScore: 0,
lowestScore: 0,
averageScore: 0,
examAttempted: 0
}
};
}
componentWillMount() {
this.updateDataForSelectedCourse(this.props.selectedCourseID);
}
componentWillReceiveProps(nextProps) {
this.updateDataForSelectedCourse(nextProps.selectedCourseID);}
updateDataForSelectedCourse(selectedCourseID = null) {
let newDataForSelectedCourse = null;
if (this.state.courseWiseScoreDetailsOfAllExams.courseID ===
selectedCourseID) {
newDataForSelectedCourse = this.state.courseWiseScoreDetailsOfAllExams;
}
this.setState({dataForSelectedCourse: newDataForSelectedCourse}, function () {
this.setChartData();
});
}