簡體   English   中英

React Hook useEffect 缺少依賴項 - 案例:分頁

[英]React Hook useEffect has missing dependencies - Case: Pagination

我在 stackoverflow 上閱讀了幾個關於 useEffect 中缺少依賴項的案例:示例: How to fix missing dependency warning when using useEffect React Hook?

現在我的情況是,我使用 useEffect 進行分頁:這是源代碼:

react-router-dom 配置

  { path: "/note", name: "My Note", exact: true, Component: Note },

音符組件

const Note = (props) => {
  const getQueryParams = () => {
    return window.location.search.replace("?", "").split("&").reduce((r, e) => ((r[e.split("=")[0]] = decodeURIComponent(e.split("=")[1])), r),
        {}
    );
  };

  const MySwal = withReactContent(Swal);
  const history = useHistory();

  // Get Queries On URL
  const { page: paramsPage, "per-page": paramsPerPage } = getQueryParams();
  
  // Queries as state
  const [queryPage, setQueryPage] = useState(
    paramsPage === undefined ? 1 : paramsPage
  );
  const [queryPerPage, setQueryPerPage] = useState(
    paramsPerPage === undefined ? 10 : paramsPerPage
  );

  // Hold Data Records as state
  const [notes, setNotes] = useState({
    loading: false,
    data: [],
    totalData: 0,
  });

  useEffect(() => {
    console.log(queryPage, queryPerPage);
    setNotes({
      ...notes,
      loading: true,
    });

    // Fetching data from API
    NoteDataService.getAll(queryPage, queryPerPage)
      .then((response) => {
        setNotes({
          loading: false,
          data: response.data,
          totalData: parseInt(response.headers["x-pagination-total-count"]),
        });

        return true;
      })
      .catch((e) => {
        MySwal.fire({
          title: e.response.status + " | " + e.response.statusText,
          text: e.response.data,
        });
      });

    return false;
  }, [queryPage, queryPerPage]);

  const { loading, data, totalData } = notes;

  ...

所以這里有兩個問題:

  1. 有一個警告React Hook use Effect has missing dependencies: 'MySwal' and 'notes'. Either include them or remove the dependency array. You can also do a functional update 'setNotes (n =>...)' if you only need 'notes' in the 'setNotes' call. React Hook use Effect has missing dependencies: 'MySwal' and 'notes'. Either include them or remove the dependency array. You can also do a functional update 'setNotes (n =>...)' if you only need 'notes' in the 'setNotes' call. 如果我添加注釋和 MySwal 作為依賴項,它會給我一個連續的循環。
  2. 當我訪問“note”頁面時,將呈現 Note 組件。 然后,用分頁: / note? Page = 2 & per-page = 10 / note? Page = 2 & per-page = 10 ,一切順利。 但是,當返回到“/note”時,頁面不會re-render 奇怪的是,如果這樣的路線/ note? Page = 1 & per-page = 10 / note? Page = 1 & per-page = 10 ,完美返回。 分頁后我的 useEffect 不運行嗎?

首先,將您的 API 調用移到 useEffect 中。 獲取數據后,您可以更改 state。

useEffect(() => {
//Fetch the data here
//setState here 
},[]) //if this array is empty, you make the api call just once, when the `component mounts`

useEffect 的第二個參數是一個依賴數組,如果你不傳遞它,你的 useEffect 將在每次渲染和更新時觸發,這是不好的。 如果你解析一個空數組,那么它只進行一次調用,如果你傳遞一個值,那么只有當傳遞的值發生變化時才反應渲染。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM