我怎样才能使状态更新比我的 axios 命令更快?

How can I make the state update sooner than my axios command?

我有这个问题,我的状态更新不够快(可能是因为我 运行 的过滤器方法,我无法避免,因为我用它来防止空从转发到我的服务器的值)最终发送一个带有错误(旧)数据的 post 请求。 这是我的代码:

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])