reactjs - 我怎样才能比我的 axios 命令更快地更新状态?
问题描述
我有这个问题,我的状态不会很快更新(可能是因为我正在运行的过滤器方法,我无法避免,因为我正在使用它来防止空值转发到我的服务器)最终发送带有错误(旧)数据的发布请求。这是我的代码:
const handleSubmit = (e) => {
setLoading(true);
e.preventDefault();
let tempInputFields = [...inputFields];
tempInputFields = tempInputFields.filter(value => value['seller'] ||
value['item'])
setInputFields(tempInputFields)
axios.post('http://localhost:3001', {
inputFields //sending tempInputFields will send the pre-filter data too.
})
.then(function (response) {
setLoading(false);
})
.catch(function (error) {
console.log(error);
});
console.log(tempInputFields) //Down here I'm getting the correct, post-filter value
};
我读到我可以使用 useEffect 作为解决方案,但我不确定如何在方法中实现它(在用户单击提交按钮后)将感谢任何输入。谢谢!
解决方案
你可以useEffect
像下面这样使用。
useEffect(() => {
if (loading) {
axios.post('http://localhost:3001', {
inputFields
})
.then(function (response) {
setLoading(false);
})
.catch(function (error) {
console.log(error);
});
}
}, [inputFields])
推荐阅读
- asp.net - 带有 Web API 的 ASP.NET MVC 5 中移动浏览器上的“404 错误 - 找不到文件或目录”错误
- ros - 螺旋桨的 ROS 模拟
- adobe-illustrator - Adobe Illustrator 脚本 - 更改选区颜色
- c# - 使用 Visual Studio 2017 的 ASP.NET 中的背景问题
- android - 一个 Activity 可以使用相同的方法使用多个 Fragment 之一吗?
- matlab - 为什么我在使用 USB1408FS 时收到错误“计数必须是数据包大小的整数倍”?
- console - 如何在 lazarus 控制台中使用 RGB 文本颜色
- javascript - 异步函数返回 [object Promise] 而不是实际值
- google-apps-script - 多个if语句在谷歌脚本中不起作用
- python - 使用 agora.io 更好的互动广播