useEffect中缺少或未使用的依赖项数组

从此处实现挂钩代码时

https://blog.logrocket.com/patterns-for-data-fetching-in-react-981ced7e5c56/

我收到以下警告,这实际上是什么意思?

./src/components/Users.tsx   20:6行:React Hook useEffect缺少依赖项:'data.users'。包括它或删除依赖项数组。如果“ setData”需要当前值“ data.users”的react-hooks / exhaustive-deps,也可以用useReducer替换多个useState变量。

码:

import React, { useEffect, useState } from "react";
import axios from "axios";
const USER_SERVICE_URL = "https://jsonplaceholder.typicode.com/users";

export function List() {
  const [data, setData] = useState({ users: [], isFetching: false });

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        setData({ users: data.users, isFetching: true });
        const response = await axios.get(USER_SERVICE_URL);
        setData({ users: response.data, isFetching: false });
      } catch (e) {
        console.log(e);
        setData({ users: data.users, isFetching: false });
      }
    };
    fetchUsers();
  }, []);

  console.log(data)
评论
  • bsit
    bsit 回复

    It means that since you use data.users in the code inside the useEffect block, and you've define an empty dependencies array, data.users might be stale.

    To solve that problem use the setState updater function. Which allows you to use the previous state, while creating the new one:

        setData(data => ({ users: data.users, isFetching: true }));
    

    要么

        setData(data => ({ users: data.users, isFetching: false }));
    

    Another options is to create a simple reducer, that will work like setState(), but will override changed items, and not the entire state:

    const reducer = (state, payload) => ({ ...state, ...payload });
    
    export function List() {
      const [data, setData] = useReducer(reducer, { users: [], isFetching: false });
    
      useEffect(() => {
        const fetchUsers = async () => {
          try {
            setData({ isFetching: true });
            const response = await axios.get(USER_SERVICE_URL);
            setData({ users: response.data, isFetching: false });
          } catch (e) {
            console.log(e);
            setData({ isFetching: false });
          }
        };
        fetchUsers();
      }, []);
    
      console.log(data)