reactjs - 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 完成更新状态?
谢谢!
解决方案
抱歉,现在我看到您正在使用 Redux。在这里,您可以使用 componentWillReceiveProps 生命周期方法并将新状态与旧状态进行比较。如果它发生了变化,您可以提出您的 XHR 请求。这是您将 redux 状态与 props 匹配的时候。
componentWillReceiveProps(nextProps){
if(nextProps.yourState!==this.props.yourState){
yourXhrRequest();
}
}
推荐阅读
- android - 内部错误。请在 MacBook 中打开 Android Studio 时向 https://code.google.com/p/android/issues 报告
- sql - How does the SQL function COALESCE() work?
- python - 我的代码部分将列表输出作为数据框列写入 csv,但之后中断
- c - OpenBSD 驱动程序开发:如何配置 GPIO 驱动程序以在用户空间中使用它?
- java - A puzzle on how Java implement volatile in new memory model (JSR 133)
- php - Nginx 中的 Laravel API 重写无法打开主脚本
- c# - 无法在 AleaTK 中使用 Context.GpuContext,因为缺少对程序集的引用。C#
- coldfusion - 网站如何显示“帮助”块,直到用户单击 X 以不再看到它们
- html - 调试目的,复杂对象类型不能转换为简单值
- tensorflow - 部署到 ML Engine 时出现 ClipByValue 错误