解决React中useEffect导致无限循环的问题
P粉018548441
P粉018548441 2023-08-14 18:47:03
0
1
475
<p>为什么这段代码在React中会产生无限循环。这里的useEffect与data和columnDataWithTaskProperty一起导致了无限循环,但我不知道为什么</p> <pre class="brush:php;toolbar:false;">const useBoard = () => { const { data: columnData } = useGetColumnQuery(); const { data } = useGetTaskAccordingToStatus(); const [columnDataWithTaskProperty, setColumnDataWithTaskProperty] = useState( [] ); const [finalState, sFinalState] = useState([]); useEffect(() => { const allColumns = columnData?.data?.map((item) => ({ name: item.name, _id: item._id, tasks: [], })); setColumnDataWithTaskProperty(allColumns); }, [columnData]); useEffect(() => { console.log("meeee data deps"); const updatedColumns = columnDataWithTaskProperty.map((column) => ({ ...column, tasks: data.flat().filter((task) => task.status === column.name), })); sFinalState(updatedColumns); }, [columnDataWithTaskProperty, data]); return { finalState, }; };</pre> <p>这里是我如何使用useGetTaskAccordingToStatus来获取数据。我使用了React Query来获取数据。</p> <pre class="brush:php;toolbar:false;">const useGetTaskAccordingToStatus = () => { const { active_project } = useSelector(projectDataInStore); const userQueries = useQueries({ queries: statesOfTaskManager.map((status) => { return { queryKey: [status, active_project], queryFn: () => customAxiosRequestForGet("/task", { status, projectName: active_project, }), onSuccess: ({ data }) => { return data; }, }; }), }); const data = userQueries?.map((item) => item?.data?.data); return { data }; };</pre> <p><br /></p>
P粉018548441
P粉018548441

全部回复(1)
P粉574695215

我建议你只使用一个use效果,并删除columnDataWithTaskProperty来测试sack,以后可以再返回它。 这是我的建议示例,但没有实际数据无法测试。

const useBoard = () => {
  const { data: columnData } = useGetColumnQuery();
  const { data } = useGetTaskAccordingToStatus();
  const [finalState, sFinalState] = useState([]);

  useEffect(() => {
    const allColumns = columnData?.data?.map((item) => ({
      name: item.name,
      _id: item._id,
      tasks: [],
    }));
      console.log("meeee data deps");
      const updatedColumns = allColumns.map((column) => ({
        ...column,
        tasks: data.flat().filter((task) => task.status === column.name),
      }));
      sFinalState(updatedColumns);
  }, [columnData, data]);

  return {
    finalState,
  };
};
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板