首页 > 解决方案 > REACT JS 类生命周期:如何将 http 请求放入 ComponentdidUpdate?

问题描述

一旦prop从 redux 商店更新,我有一个 http 请求要调用,如下所示:

const mapStateToProps = state => {
  console.log(state.queryBuild);
  return {
      queryBuilderObject: state.queryBuild,
  }

}

export default connect(mapStateToProps, null)(SummaryView);

这是我的componentdidupdate功能:

async componentDidUpdate()
  {
    //console.log("Component unmount detected");
    //console.log(this.props.queryBuilderObject);
    this.setState({state: {
      ...this.state,
      isLoading: true,
    }});
    await axios.post(ApiEndPoints.getSummaryDataByQueryBuilder,this.props.queryBuilderObject,{timeout: axiosTimeOut})
    .then(response => {
      console.log("REsponse:");
      console.log(response);
          this.setState({state: {
            ...this.state,
            isLoading: false,
          }});
    })
    .catch(error => console.log("Error: " + error.message));


  }

props.queryBuilderObject现在这是问题所在......不知何故,如果来自 redux 商店的更改,我只想发出一个 http 请求。但是当我这样做时,我在设置状态时进入了一个无限循环,因此每次都会触发 componentdidupdate。

有人可以建议这样做的正确方法吗?

标签: reactjsreact-redux

解决方案


componentDidUpdate接收先前的道具和状态作为参数,您可以检查先前的道具'queryBuilderObject与当前道具' queryBuilderObject,如果它们不相等,则执行 POST 请求。

componentDidUpdate(prevProps, prevState, 快照)

可以setState()立即调用,componentDidUpdate()但请注意它必须包含在一个条件中

如果您在没有条件检查的情况下从此生命周期函数更新状态,则可能会导致无限渲染循环。

也不需要在setState函数中以现有状态进行传播;setState对状态更新进行浅合并。

async componentDidUpdate(prevProps) {
  if (prevProps.queryBuilderObject !== this.props.queryBuilderObject) {
    this.setState({ isLoading: true });
    await axios
      .post(
        ApiEndPoints.getSummaryDataByQueryBuilder,
        this.props.queryBuilderObject,
        { timeout: axiosTimeOut }
      )
      .then((response) => {
        this.setState({ isLoading: false });
      })
      .catch((error) => console.log("Error: " + error.message));
  }
}

推荐阅读