简体   繁体   English

redux useEffect 和 useDispatch 不起作用(最大调用堆栈)?

[英]redux useEffect and useDispatch not working (max call stack)?

I am new to redux hooks and react hooks and this is my code that doesn't stop rendering?我是 redux hooks 和 react hooks 的新手,这是我的代码不会停止渲染?

const App: React.FC = () => {
  const dispatch = useDispatch();
  const [page, setPage] = useState(1);
  const fetchUsers = async (page: number) => {
    dispatch({
      type: FETCH_USERS_REQUEST,
      payload: { page }
    });
    try {
      const { data, ...result } = await api.fetchUsers(page);
      const user = new schema.Entity('data');
      const users = normalize(
        { users: data },
        {
          users: [user]
        }
      );
      dispatch({
        type: FETCH_USERS_SUCCESS,
        payload: {
          ...result,
          users
        }
      });
    } catch (error) {
      dispatch({ type: FETCH_USERS_FAILURE, payload: { error } });
    }
  };
  useEffect(() => {
    fetchUsers(1);
  }, [fetchUsers]);
  const users = useSelector((state: RootState) => state.users);
  console.log('asd', users);
  return (
    <div className="vh-100 vw-100">
      <header>Users</header>asdasd
    </div>
  );
};

fetchUsers is an async method that i plan to use multiple times on loadMore and pagination, however, this is not working, how do i make it work? fetchUsers 是一种异步方法,我计划在 loadMore 和分页上多次使用,但是,这不起作用,我该如何使其工作?

Your fetchUsers is changing on each rerender that is casing your useEffect with that fetch to trigger.您的 fetchUsers 在每次重新渲染时都会发生变化,这些重新渲染将您的 useEffect 与该 fetch 一起触发。

Try this:尝试这个:

  useEffect(() => {
    fetchUsers(pageNumber);
  }, [pageNumber]);

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

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