首頁  >  問答  >  主體

解決React中useEffect導致無限循環的問題

<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粉018548441P粉018548441454 天前434

全部回覆(1)我來回復

  • P粉574695215

    P粉5746952152023-08-15 12:13:13

    我建議你只使用一個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,
      };
    };

    回覆
    0
  • 取消回覆