![](/img/trans.png)
[英]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.