我想在我的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是的我应该确实...我可以验证数据是完全正确的。 –