[英]State does not get updated in functional component in React for the first time after axios call
[英]React: State does not get updated after AJAX call
我试图在我的React项目中进行两个AJAX调用,并根据接收到的数据渲染UI。 这是我的渲染方法:
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>
)
}
}
render方法检查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,之后再没有任何运行。
我究竟做错了什么? 谢谢!
fetch的json()方法返回一个promise。 您在第一个调用中正确使用了它,但是在第二个调用中,您将其视为函数而非promise。
尝试
gradeResponse.json().then((gradeData) => {
...
});
您需要在componentDidUpdate中编写此逻辑。 componentDidMount将仅在第一次触发。
请参考React 文档。
可能您将需要componentDidMount和componentDidUpdate。
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
this.setState({
examsLoaded: true
}); //At this point some state is changed, so componentDidUpdate will be triggered. Then in that function below, grades will be fetched and state is changed, which should call render again.
});
});
},
componentDidUpdate(){
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
});
});
});
}
由于我现在没有反应环境。 我会尽快更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.