【问题标题】:React Hook useEffect has a missing dependency: 'History'React Hook useEffect 缺少依赖项:'History'
【发布时间】:2021-03-29 19:25:36
【问题描述】:

我有这个代码:

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”

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

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

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

    【讨论】:

    • 我该怎么做
    • 在依赖数组中添加历史记录。
    • 带有“数据”[数据,历史]
    • History.push("/") 不更改历史记录吗?
    猜你喜欢
    • 2021-02-23
    • 2019-10-24
    • 2020-10-26
    • 2020-03-07
    • 2020-02-25
    • 2020-06-11
    • 2020-03-30
    • 2020-12-29
    • 2019-09-20
    相关资源
    最近更新 更多