首页 > 解决方案 > React / Redux - 根据状态变化创建 XHR 请求

问题描述

我有一个从按钮单击中调用的方法。在这种方法中,我在真或假之间切换某些状态。切换状态后,我需要使用刚刚更改的状态向服务器发出 XHR 请求。

handleButtonClick = () => {
    //toggle 'in_progress' state attribute to false or true
    this.toggleInProgressState();

    //redux widget state
    const { state } = this.props;

    //Send data to server 
    const data = {};
    data.in_progress = state.in_progress;
    axios.patch(`/api/v1/somewhere}/`, data)
        .then((response) => {
            console.log(response);
        })
        .catch((error) => {
            console.log(error);
        });
}

我遇到的问题是我发送到服务器的状态不是应用程序的实际状态。我相信这很可能是因为 React 还没有完成渲染。在我发送 XHR 之前,如何确保 React 完成更新状态?

谢谢!

标签: reactjsreduxaxios

解决方案


抱歉,现在我看到您正在使用 Redux。在这里,您可以使用 componentWillReceiveProps 生命周期方法并将新状态与旧状态进行比较。如果它发生了变化,您可以提出您的 XHR 请求。这是您将 redux 状态与 props 匹配的时候。

componentWillReceiveProps(nextProps){
  if(nextProps.yourState!==this.props.yourState){
    yourXhrRequest();
  }
}

推荐阅读