【问题标题】:Why componentDidUpdate is executing repeatedly为什么 componentDidUpdate 重复执行
【发布时间】:2020-03-27 17:21:13
【问题描述】:

我正在尝试在提交时显示用户注释。在 componentDidMount 上,我正在向服务器发送一个 GET 请求以最初显示数据。当用户提交新评论时,我在 componentDidUpdate 上检查 prevState。如果发现任何差异,它应该从服务器加载新数据。

但是在 componentDidUpdate 内部连续请求正在发送到服务器。

到目前为止我做了什么

componentDidUpdate(prevProps, prevState){
    if(prevState.status !== this.props.userDisplayNotes.status){

            // This is GET request to display the data from the server

            this.props.displayUserNotes(this.props.user_id)

    }
}


// Here I'm displaying data on initial rendering with GET request

componentDidMount(){
    this.props.displayUserNotes(this.props.user_id)
}

// This is form submit handler

handleSubmit = (e) => {      
    e.preventDefault();
    this.props.saveUserNote(this.props.user_id, this.state.userNote)

}

成功提交评论后,我会收到来自服务器的响应,例如 {"status":"success"}

我使用 Redux 进行状态管理。

但在 componentDidUpdate 内部,它正在向服务器发送连续请求,导致应用程序崩溃。有人可以解释一下我在这里做错了什么吗?

【问题讨论】:

  • 如果你 console.logprevState.statusthis.props.userDisplayNotes.status 在检查它们是否相等之前会很好
  • console.log prevState.status 显示未定义,this.props.userDisplayNotes.status 显示成功
  • 它们不相等,因此被重复调用
  • this.state.status 设置在哪里?你的意思是检查prevProps?如if(prevProps.userDisplayNotes.status !== this.props.userDisplayNotes.status)
  • @Sallf 非常感谢。相比之下我错了。我遵循了您的方法并且效果很好。

标签: reactjs redux react-component react-lifecycle-hooks


【解决方案1】:

您可以将以前的道具与新道具进行比较,它将解决您的问题

componentDidUpdate(prevProps, prevState){
if(prevProps.userDisplayNotes.status !== this.props.userDisplayNotes.status){
        this.props.displayUserNotes(this.props.user_id)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 2017-12-06
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    相关资源
    最近更新 更多