在useEffect中调用分派以调用一个thunk,开始无限循环

问题描述 投票:1回答:1

我的项目路由结构的一部分:

<Dashboard>
    <Topbar />

    <Switch>
      <PrivateRoute exact path={path}>
        <WelcomeBox name={user.display_name} />

        <Categories
          isLoading={content.categories.length === 0}
          categories={content.categories}
          url={url}
        /> // No trouble
      </PrivateRoute>

      <PrivateRoute exact path={`${path}/:categoryId`}>
        <PlaylistsRoute path={path} /> // Infinite loop
      </PrivateRoute>

      <PrivateRoute exact path={`${path}/:categoryId/:playlistId`}>
        <TracksRoute path={path} /> // Infinite loop
      </PrivateRoute>
    </Switch>
  </Dashboard>

我的一条集装箱路线是使用Route渲染道具渲染的:

const PrivateRoute = ({ comp: Component, ...rest }) => {
  const isLogged = useSelector((state) => state.auth.isLogged);

  return (
    <Route
      {...rest}
      render={(props) =>
        !isLogged ? <Redirect to="/" /> : <Component {...props} />
      }
    />
  );
};

此容器组件具有对端点的API调用,实际上是使用对thunk(fetchPlaylists)的调用:

useEffect(() => {
  dispatch(fetchPlaylists(categoryId));
}, [dispatch, categoryId]);

它最终陷入无限循环:

enter image description here

我想知道是什么原因引起的,因为我在同级Route中进行了类似的调用而没有任何麻烦。

reactjs react-redux react-router-dom redux-thunk use-effect
1个回答
0
投票
useEffect(() => { onFetchPlaylists(categoryId); }, [categoryId]);

这种方式useEffect仅应在组件安装时以及每次categoryId更改时触发。

© www.soinside.com 2019 - 2024. All rights reserved.