简体   繁体   English

React Cleanup 异步函数获取钩子

[英]React Cleanup async function fetch with hooks

This is in a functional component.这是在一个功能组件中。

I have a submit() function that looks like so:我有一个submit()函数,看起来像这样:

  async function handleSubmit(event) {
    event.preventDefault();
    try {
      let resp = await fetch("FOOBAR/BAX", {
        method: 'POST',
        body: JSON.stringify({ /*stuff*/})
      });
      if (resp.ok){
        // yadda yadda yadda
        props.history.push("/"); // navigate
      }
    } 
  } 

Now, when I cause navigation to occur I'm getting the dreaded 'Can't perform a React state update on an unmounted component.'现在,当我导致导航发生时,我得到了可怕的“无法在未安装的组件上执行 React 状态更新”。 error.错误。

So, using effects, how do I make sure this fetch call is cleaned up?那么,使用效果,我如何确保清除此 fetch 调用? All the examples I'm seeing use useEffect to both set up and then cleanup the call (with cleanup function).我看到的所有示例都使用useEffect来设置和清理调用(使用清理函数)。

Clean up a fetch request by cancelling on dismount using an abort controller通过使用中止控制器取消卸载来清理获取请求

Factor the fetch request logic out of the handler into the effect hook and use a state hook to trigger the effect to fire.将处理程序中的 fetch 请求逻辑分解到效果钩子中,并使用状态钩子来触发效果触发。 Return the controller's abort function in the effect hook to be called when the component unmounts.在组件卸载时调用的 effect hook 中返回控制器的abort函数。

const [body, setBody] = useState('');

useEffect(() => {
  const controller = new AbortController();
  const signal = controller.signal;

  if (body) {
    fetch("FOOBAR/BAX", {
      method: 'POST',
      body: JSON.stringify(body),
      signal, // add signal to request
    })
    .then(res => {
      setBody(''); // clear request body value
      if (res.ok) props.history.push('/');
    });
  }

  return controller.abort; // return the abort function to be called when component unmounts
}, [body]);

const handleSubmit = (event) => {
  event.preventDefault();
  setBody({ /*stuff*/ }); // set request body value to trigger effect to fetch
};

Here's a codesandbox with this implemented as a react hook, with manual abort and automatic abort on unmounting.这是一个代码沙盒,它作为反应钩子实现,手动中止和卸载时自动中止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM