在函数调用之前设置 React hooks 状态

Setting React hooks state before function call

我在 resetStates 中调用 handleSearchClick 函数之前设置 page = 1 时遇到问题。目前,当调用 resetStates 时(在单击 search button 之后),它不会在第一次点击时将页面重置为 1,但在第二次搜索时会重置。

我尝试使用 async await 但那不是在 handleSearchClick 之前将页面重置为 1。如何在函数调用前将页面重置为 1?任何反馈表示赞赏。

这是我目前正在做的事情:

const resetStates = async () => {
            const promise1 = setHasMore(true);
            const promise2 = await setPage(1);
            Promise.all([promise1, promise2])
                .then(() => {
                 /* At this point I want page to equal 1 */
                    handleSearchClick(); 
                })
                .catch(error => {
                    throw new Error(error);
                });
        };

    /**
     * Handles event on search click
     */
    const handleSearchClick = async () => {
        setItems([]);
        setIsLoading(true);
        const base = handleBaseId();
        const items = await fetchSearchPayload(page, value, option, base);
        setIsLoading(false);
        setInitialLoad(true);
        setItems(items);
        console.log('On Click', { option }, { page });
    };

 <SearchBar
    onClickButton={resetStates}
    onValueChange={handleChange}
    value={value}
    pageNum={page}
    onEnter={handleSearchOnEnter}
  />

state updater is asynchronous,但它不是 return 你的承诺,所以你不能使用 await 来等待承诺完成。相反,您可以将页面值作为参数传递

    const resetStates = async () => {
            setHasMore(true);
            setPage(1);
            handleSearchClick(1); 
    };

    /**
     * Handles event on search click
     */
    const handleSearchClick = async (page) => {
        setItems([]);
        setIsLoading(true);
        const base = handleBaseId();
        const items = await fetchSearchPayload(page, value, option, base);
        setIsLoading(false);
        setInitialLoad(true);
        setItems(items);
        console.log('On Click', { option }, { page });
    };

 <SearchBar
    onClickButton={resetStates}
    onValueChange={handleChange}
    value={value}
    pageNum={page}
    onEnter={handleSearchOnEnter}
  />

否则你可以利用useEffect等待状态更新

const prevPage = usePrevious(page);
const prevHasMore = usePrevious(hasMore);
const initialRender = useRef(true);
useEffect(() => {
   if(initialRender.current !== true) {
        // you can check for hasMore also here
        if((prevPage !== page && page == 1) && (prevHasMore !== hasMore && hasMore === true)) {
            handleSearchClick();
        }
   }
}, [hasMore, page])

const resetStates = async () => {
        setHasMore(true);
        setPage(1);

};

/**
 * Handles event on search click
 */
const handleSearchClick = async (page) => {
    setItems([]);
    setIsLoading(true);
    const base = handleBaseId();
    const items = await fetchSearchPayload(page, value, option, base);
    setIsLoading(false);
    setInitialLoad(true);
    setItems(items);
    console.log('On Click', { option }, { page });
};

可以参考下面usePrevious的实现post