如何在React Hooks的setState完成后解决一个Promise?

4

在React Hooks中,setState(useState)没有回调函数,因此我需要在setState完成后解决promise。

此代码的React Hooks版本:

handleBeforeGetContent = () => {
    return new Promise((resolve, reject) => {
        this.setState({ key: 'updatedValue' }, () => resolve());
    });
}
3个回答

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();
      }, []);

5

您可以使用useEffect作为useEffect的参数,每当状态发生更改时都会运行,绕过您想要观察的期望状态。

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

0
你可以在使用自定义的useState钩子时,使用一种叫做回调的东西来设置状态。
下面的代码演示了这一点。

const useStateWithCallback = (initialValue) => {
  const cbRef = React.useRef();
  const [state, setState] = React.useState(initialValue);
  React.useEffect(() => {
    if (cbRef.current) {
      cbRef.current(); // calls the callback after setState has finished
      cbRef.current = null; // reset for next cb
    }
  }, [state]);

  const setStateWithCallback = (setter, cb) => {
    if (cb) cbRef.current = cb; // save the cb to call after setState is finished in useEffect above.
    if (typeof setter === "function") {
      setState(setter(state));
    } else {
      setState(setter);
    }
  };

  return [state, setStateWithCallback];
};

// usage
const Counter = (props) => {

  const [count, setCount] = useStateWithCallback(0);
  const [state, setState] = useStateWithCallback(null);

  const incrementAndDoSomething = () => {
    setCount((prev) => prev + 1, () => console.log('Do something when setState has finished'));
  }

  // your usecase
  handleBeforeGetContent = () => {
    return new Promise((resolve, reject) => {
      setState({
        key: 'updatedValue'
      }, () => resolve());
    });
  }
  return <h1 > {
    count
  } < /h1>;
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接