React Hook useEffect 缺少依赖项:'History'

时间:2020-12-19 10:42:08

标签: reactjs react-hooks

我有这个代码:

import {useContext, useEffect, useState} from 'react';
import {useHistory} from "react-router-dom";
import {MasterContext} from "../../Context/MasterProvider";
import LoginActions from "../../Context/Actions/LoginActions";

const useLoginForm = () => {
    const History = useHistory();
    const [login, setLogin] = useState({});
    const {AuthState: {Authentication: {Loading, Data, Error}}, AuthDispatch}=useContext(MasterContext);
    const FormData = (event) => {
        const { target: { value, name } } = event;
        setLogin({...login, [name]: value});
    };

    const FormValid =
        !login.email?.length ||
        !login.password?.length;

    const FormSubmit = () => {
        LoginActions(login)(AuthDispatch);
    }

    useEffect(() => {
        if(Data) {
            if(Data.user) {
                History.push("/");
            }
        }
    }, [Data])

        return {login, FormData, FormValid, FormSubmit, Loading, Error, Data};
    }

export default useLoginForm;

它工作正常,但有警告。 “React Hook useEffect 缺少依赖项:'History'。要么包含它,要么删除依赖项数组 react-hooks/exhaustive-deps”

1 个答案:

答案 0 :(得分:1)

您可以添加 History 作为依赖项,除非更改路由,否则 History 不会更改。因此,除非数据或历史记录发生更改,否则您的 useEffect 钩子不会运行。

  useEffect(() => {
        if(Data && Data.user) {
                History.push("/");
        }
    }, [Data, History])