首页 > 解决方案 > 我怎样才能比我的 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 作为解决方案,但我不确定如何在方法中实现它(在用户单击提交按钮后)将感谢任何输入。谢谢!

标签: reactjsreact-hooksuse-state

解决方案


你可以useEffect像下面这样使用。

useEffect(() => {
  if (loading) {
    axios.post('http://localhost:3001', {
      inputFields
    })
    .then(function (response) {
      setLoading(false);
    })
    .catch(function (error) {
      console.log(error);
    });
  }
}, [inputFields])

推荐阅读