我想在我的React項目中做兩個AJAX調用,並根據收到的數據讓我的UI呈現。這是我的渲染方法:反應:狀態不會在AJAX調用後得到更新
render() {
if (this.state.examsLoaded) {
return (
<div>
<Button onClick={this.openModal}>Details</Button>
<Modal show={this.state.modalOpen} onHide={this.closeModal}>
<Modal.Header closeButton>
<Modal.Title>{this.props.course.name}</Modal.Title>
</Modal.Header>
<Modal.Body>
<DetailModalContent course={this.props.course} exams={this.exams} grades={this.grades}/>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.closeModal}>Sluiten</Button>
</Modal.Footer>
</Modal>
</div>
)
}
else {
return (
<div>Loading...</div>
)
}
}
渲染方法檢查AJAX數據可用但如果沒有,只是呈現一個「正在載入」消息。這是提取數據的代碼:
componentDidMount() {
fetch('http://localhost:8080/course/' + this.props.course.id + '/exams').then((examResp) => {
examResp.json().then((examData) => {
this.exams = examData;
console.log('Course data fetched'); // THIS APPEARS
fetch('http://localhost:8080/user/1/grades').then((gradeResponse) => { // THIS DATA IS FETCHED
console.log('Done fetching grades'); // THIS APPEARS
gradeResponse.json((gradeData) => {
console.log('Parsed JSON'); // Here is where it goes wrong. This no longer appears.
this.grades = gradeData;
this.setState({
examsLoaded: true,
modalOpen: false
});
});
});
});
});
},
奇怪的是,我以前只有1個提取方法,一切都會正常工作。只要我呼叫setState
,組件會重新顯示並顯示數據。但是,添加第二個後,它不再工作。看我的console.log
的。一切工作正常「,直到我解析JSON,之後,沒有任何東西可以運行了。
我在做什麼錯? 謝謝!
在一個側面說明,你應該在組件的狀態下保存數據,而不是直接作爲道具(this.grades)。你能驗證第二個Ajax調用的返回值是什麼嗎?也許它是畸形的? –
@TMitchell是的我應該確實...我可以驗證數據是完全正確的。 –