简体   繁体   English

如何使用带有 componentDidUpdate 和 setState 的 react js 更新 state?

[英]How to update state with react js with componentDidUpdate and setState?

How to update the data with react js eg a user writes a comment how to make this messages show up to all other users?如何使用 react js 更新数据,例如用户写评论如何使此消息显示给所有其他用户? I used setState in componentDidUpdate with a stop condition but it doesn't work.我在 componentDidUpdate 中使用了 setState 并带有停止条件,但它不起作用。 If i don't make a condition, it work correctely but with infinite loop.如果我不设定条件,它会正常工作,但会无限循环。

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);

} } } }

If your looking to update every second, you can initialize a timer when component mounts.如果您希望每秒更新一次,您可以在组件挂载时初始化一个计时器。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM