简体   繁体   中英

React `useState` hooks - set the state and use it immediately

I understand that changing the state causes the component function to be called again with the new state being derived from the useState hook. Within the function where the state is set, the state remains the same because any functions defined inside it close over that state.

Here's an example of where I'm having trouble finding a good pattern:

  const fetchUsers = async () => {
    const result = await axios.get(
      `http://localhost:3001/get_users/${pageNumber}`
    );
   }

  const loadMore = () => {
    setPageNumber(pageNumber + 1);
    fetchUsers();
  };

Of course this doesn't work because fetchUsers doesn't have access to the updated state.

  const loadMore = () => {
    setPageNumber(pageNumber + 1);
    fetchUsers(pageNumber + 1);
  };

I could do this but it seems less clear. Is there a better way?

You can call fetchUsers inside useEffect with pageNumber as the dependency.

useEffect(fetchUsers, [pageNumber])

useEffect will call fetchUsers whenever pageNumber changes.

For this you can use the useEffect hook. You can give it a function and an array as parameters. If any of the variables in the array changes (such as a state var you give to it) the function will be called. You'll be able to use the newest pageNumber inside there.

const [ pageNumber, setPageNumber ] = useState(1);

const loadMore = () => {
    setPageNumber(pageNumber + 1);
};

/* Be careful, this function will also run on mount. If you want to prevent that make use of some isMounted boolean inside it. */
useEffect(() => {
    fetchUsers(pageNumber);
}, [ pageNumber ]);

const fetchUsers = async (toFetchPageNumber) => {
    const result = await axios.get(
        `http://localhost:3001/get_users/${toFetchPageNumber}`
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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