使用反应钩子在更新状态时执行异步代码



我有这样的东西:

const [loading, setLoading] = useState(false);
...
setLoading(true);
doSomething(); // <--- when here, loading is still false. 

设置状态仍然是异步的,那么等待此setLoading()调用完成的最佳方法是什么?

setLoading()似乎不像以前那样接受回调setState()

一个例子

基于类

getNextPage = () => {
    // This will scroll back to the top, and also trigger the prefetch for the next page on the way up.
    goToTop();
    if (this.state.pagesSeen.includes(this.state.page + 1)) {
      return this.setState({
        page: this.state.page + 1,
      });
    }
    if (this.state.prefetchedOrders) {
      const allOrders = this.state.orders.concat(this.state.prefetchedOrders);
      return this.setState({
        orders: allOrders,
        page: this.state.page + 1,
        pagesSeen: [...this.state.pagesSeen, this.state.page + 1],
        prefetchedOrders: null,
      });
    }
    this.setState(
      {
        isLoading: true,
      },
      () => {
        getOrders({
          page: this.state.page + 1,
          query: this.state.query,
          held: this.state.holdMode,
          statuses: filterMap[this.state.filterBy],
        })
          .then((o) => {
            const { orders } = o.data;
            const allOrders = this.state.orders.concat(orders);
            this.setState({
              orders: allOrders,
              isLoading: false,
              page: this.state.page + 1,
              pagesSeen: [...this.state.pagesSeen, this.state.page + 1],
              // Just in case we're in the middle of a prefetch.
              prefetchedOrders: null,
            });
          })
          .catch(e => console.error(e.message));
      },
    );
  };

转换为基于函数

  const getNextPage = () => {
    // This will scroll back to the top, and also trigger the prefetch for the next page on the way up.
    goToTop();
    if (pagesSeen.includes(page + 1)) {
      return setPage(page + 1);
    }
    if (prefetchedOrders) {
      const allOrders = orders.concat(prefetchedOrders);
      setOrders(allOrders);
      setPage(page + 1);
      setPagesSeen([...pagesSeen, page + 1]);
      setPrefetchedOrders(null);
      return;
    }
    setIsLoading(true);
    getOrders({
      page: page + 1,
      query: localQuery,
      held: localHoldMode,
      statuses: filterMap[filterBy],
    })
      .then((o) => {
        const { orders: fetchedOrders } = o.data;
        const allOrders = orders.concat(fetchedOrders);
        setOrders(allOrders);
        setPage(page + 1);
        setPagesSeen([...pagesSeen, page + 1]);
        setPrefetchedOrders(null);
        setIsLoading(false);
      })
      .catch(e => console.error(e.message));
  };

在上面,我们希望按顺序运行每个 setWhatever 调用。这是否意味着我们需要设置许多不同的 useEffect 钩子来复制此行为?

useState setter 在状态更新完成后不会像 React 类组件中的 setState 那样提供回调。为了复制相同的行为,您可以使用类似的模式componentDidUpdate例如 React 类组件中的生命周期方法,并使用 Hook useEffect

useEffect钩子将第二个参数作为值数组,React 需要在渲染周期完成后监控其更改。

const [loading, setLoading] = useState(false);
...
useEffect(() => {
    doSomething(); // This is be executed when `loading` state changes
}, [loading])
setLoading(true);

编辑

setState 不同,useState钩子的更新程序没有回调,但您始终可以使用useEffect来复制上述行为。但是,您需要确定加载更改

代码的函数式方法如下所示

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

const prevLoading = usePrevious(isLoading);
useEffect(() => {
   if (!prevLoading && isLoading) {
       getOrders({
          page: page + 1,
          query: localQuery,
          held: localHoldMode,
          statuses: filterMap[filterBy],
      })
      .then((o) => {
        const { orders: fetchedOrders } = o.data;
        const allOrders = orders.concat(fetchedOrders);
        setOrders(allOrders);
        setPage(page + 1);
        setPagesSeen([...pagesSeen, page + 1]);
        setPrefetchedOrders(null);
        setIsLoading(false);
      })
      .catch(e => console.error(e.message));
   }
}, [isLoading, preFetchedOrders, orders, page, pagesSeen]);
const getNextPage = () => {
    // This will scroll back to the top, and also trigger the prefetch for the next page on the way up.
    goToTop();
    if (pagesSeen.includes(page + 1)) {
      return setPage(page + 1);
    }
    if (prefetchedOrders) {
      const allOrders = orders.concat(prefetchedOrders);
      setOrders(allOrders);
      setPage(page + 1);
      setPagesSeen([...pagesSeen, page + 1]);
      setPrefetchedOrders(null);
      return;
    }
    setIsLoading(true);
  };

等到组件重新渲染。

const [loading, setLoading] = useState(false);
useEffect(() => {
    if (loading) {
        doSomething();
    }
}, [loading]);
setLoading(true);

您可以通过以下方式提高清晰度:

function doSomething() {
  // your side effects
  // return () => {  }
}
function useEffectIf(condition, fn) {
  useEffect(() => condition && fn(), [condition])
}
function App() {
  const [loading, setLoading] = useState(false);
  useEffectIf(loading, doSomething)
  return (
    <>
      <div>{loading}</div>
      <button onClick={() => setLoading(true)}>Click Me</button>
    </>
  );
}

创建了一个自定义useState钩子,其工作原理类似于普通的useState钩子,只是此自定义钩子的状态更新程序函数接受将在状态更新和组件重新渲染后执行的回调。

打字稿解决方案

import { useEffect, useRef, useState } from 'react';
type OnUpdateCallback<T> = (s: T) => void;
type SetStateUpdaterCallback<T> = (s: T) => T;
type SetStateAction<T> = (newState: T | SetStateUpdaterCallback<T>, callback?: OnUpdateCallback<T>) => void;
export function useCustomState<T>(init: T): [T, SetStateAction<T>];
export function useCustomState<T = undefined>(init?: T): [T | undefined, SetStateAction<T | undefined>];
export function useCustomState<T>(init: T): [T, SetStateAction<T>] {
    const [state, setState] = useState<T>(init);
    const cbRef = useRef<OnUpdateCallback<T>>();
    const setCustomState: SetStateAction<T> = (newState, callback?): void => {
        cbRef.current = callback;
        setState(newState);
    };
    useEffect(() => {
        if (cbRef.current) {
            cbRef.current(state);
        }
        cbRef.current = undefined;
    }, [state]);
    return [state, setCustomState];
}

Javascript 解决方案

import { useEffect, useRef, useState } from 'react';
export function useCustomState(init) {
    const [state, setState] = useState(init);
    const cbRef = useRef();
    const setCustomState = (newState, callback) => {
        cbRef.current = callback;
        setState(newState);
    };
    useEffect(() => {
        if (cbRef.current) {
            cbRef.current(state);
        }
        cbRef.current = undefined;
    }, [state]);
    return [state, setCustomState];
}

用法

const [state, setState] = useCustomState(myInitialValue);
...
setState(myNewValueOrStateUpdaterCallback, () => {
   // Function called after state update and component rerender
})
你可以

创建一个异步状态钩子

const useAsyncState = initialState => {
  const [state, setState] = useState(initialState);
  const asyncSetState = value => {
    return new Promise(resolve => {
      setState(value);
      setState((current) => {
        resolve(current);
        return current;
      });
    });
  };
  return [state, asyncSetState];
};

然后

const [loading, setLoading] = useAsyncState(false)
const submit = async () => {
  await setLoading(true)
  dosomething() 
}

将函数传递给 setter 而不是值!

不要直接向资源库提供新值,而是向它传递一个箭头函数,该函数采用当前状态值并返回新值。

它将

强制它链接状态更新,并在完成所有状态更新后,它将重新渲染组件。

const [counter, setCounter] = useState(0);
const incrementCount = () => {
    setCounter( (counter) => { return counter + 1 } )
}

现在每次调用增量计数时,它都会将计数增加 1,并且不再停留在 1。

我对此有一个建议。

你可以使用 React Ref 来存储状态变量的状态。然后用反应引用更新状态变量。这将呈现页面刷新,然后在异步函数中使用 React Ref。

const stateRef = React.useRef().current
const [state,setState] = useState(stateRef);
async function some() {
  stateRef = { some: 'value' }
  setState(stateRef) // Triggers re-render
  
  await some2();
}
async function some2() {
  await someHTTPFunctionCall(stateRef.some)
  stateRef = null;
  setState(stateRef) // Triggers re-render
}

相关内容

  • 没有找到相关文章

最新更新