简体   繁体   English

React`useState`钩子-设置状态并立即使用

[英]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. 我知道更改状态会导致组件函数被再次调用,而新的状态是从useState挂钩派生的。 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. 当然,这是行不通的,因为fetchUsers无法访问更新后的状态。

  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以pageNumber作为依赖项调用fetchUsers。

useEffect(fetchUsers, [pageNumber])

useEffect will call fetchUsers whenever pageNumber changes. 当pageNumber更改时,useEffect将调用fetchUsers。

For this you can use the useEffect hook. 为此,您可以使用useEffect挂钩。 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. 如果数组中的任何变量发生更改(例如您赋予它的状态var),则将调用该函数。 You'll be able to use the newest pageNumber inside there. 您将可以在其中使用最新的pageNumber。

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}`
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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