React hooks setState 完成后如何解决 Promise?

Cha*_*rei 4 promise setstate reactjs react-hooks

我需要在 setState 完成后解决承诺,但在 React hooks setState (useState) 中没有回调函数。

此代码的 React hooks 版本:

handleBeforeGetContent = () => {
    return new Promise((resolve, reject) => {
        this.setState({ key: 'updatedValue' }, () => resolve());
    });
}
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以在 useEffect 中使用异步函数,如下所示。

  const [isLoadingComplete, setLoadingComplete] = React.useState(false);


  React.useEffect(() => {
        async function loadDataAsync() {
          try {    
            await loadAsyncSomething();
          } catch (e) {
            console.warn(e);
          } finally {
            setLoadingComplete(true);
          }
        }

        loadDataAsync();
      }, []);
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用 useEffect 来运行每个状态更改,绕过您想要作为 useEffect 中的参数观察的所需状态。

React.useEffect(() => {
    //your callback function can be executed here after the updatedValue updated
  }, [updatedValue]);
Run Code Online (Sandbox Code Playgroud)