反应钩子 | useEffect :为什么这些钩子中的一个而不是两个都有依赖项 lint 错误?

时间:2020-12-29 17:05:22

标签: javascript reactjs react-hooks use-effect

如果 state.zip 更改,则再次调用 'getLocations'。没有警告。 'locations' 或 'testFilter' 更新后,调用 filterSearchLocations 来设置显示给用户的 'searchLocations' 的状态。以下 ESLint 错误:

 Line 91:6:  React Hook useEffect has a missing dependency: 'filterSearchLocations'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

为什么在第二个 useEffect 上抛出这个警告而不是第一个?

  const getLocations = async () => {
    setFetching(true);
    try {
      const res = await axios.get('http://localhost:8000/common/locations');
      dispatch({ type: SET_ALL_LOCATIONS, payload: res.data });
    } catch (e) {
      console.log(e);
      dispatch({ type: SET_ERROR, payload: e.message });
    } finally {
      setFetching(false);
    }
  };

  const filterSearchLocations = () => {
    const searchLocations =
      Object.keys(state.testFilter).length === 0
        ? state.allLocations
        : state.allLocations.filter((location) => {
            for (let [test] of Object.entries(state.testFilter)) {
              if (state.testFilter[test] && location.tests.indexOf(test) === -1)
                return false;
            }
            return true;
          });
    dispatch({ type: SET_SEARCH_LOCATIONS, payload: searchLocations });
  };

  // get distances
  useEffect(() => {
    getLocations();
  }, [state.zip]);

  // filter search locations
  useEffect(() => {
    filterSearchLocations();
  }, [state.allLocations, state.testFilter]);

0 个答案:

没有答案
相关问题