[英]How to update state with react js with componentDidUpdate and setState?
如何使用 react js 更新數據,例如用戶寫評論如何使此消息顯示給所有其他用戶? 我在 componentDidUpdate 中使用了 setState 並帶有停止條件,但它不起作用。 如果我不設定條件,它會正常工作,但會無限循環。
componentDidUpdate(prevProps, prevState) {
console.log("1" + prevState.changeRepComm.toString())
console.log("2" + this.state.changeRepComm.toString())
if (prevState.changeRepComm !== this.state.changeRepComm ) {
if (this.updateTimer) return;
this.updateTimer = setTimeout(() => {
//lister response comments
fetch('/api/ReponseCommentaire/listerReponseCommentaire', {
method: "GET",
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(response => {
console.log('Ajouter response:' + JSON.stringify(response))
this.setState({ ...this.state, reponseCommentaires: response });
})
.catch((err) => {
console.log('fetch failed => ', err);
})
}, 1000);
} }
如果您希望每秒更新一次,您可以在組件掛載時初始化一個計時器。
componentDidMount(prevProps, prevState) {
if (this.updateTimer) { return; }
this.updateTimer = setInterval(() => {
fetch('/api/ReponseCommentaire/listerReponseCommentaire', {
method: "GET",
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(response => {
this.setState({
...this.state,
reponseCommentaires: response,
});
})
.catch((err) => console.log('fetch failed => ', err) )
}, 1000);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.