0

我试图将一个函数分离到另一个文件中,并在useEffect(). 这是我的代码。

ReadCookie.js

import React, {useContext} from 'react'
import { AuthContext } from '../App';
import Cookies from 'js-cookie';
import { useHistory } from 'react-router-dom';

export const ReadCookie = () => {
    const {setAuthenticated} = useContext(AuthContext);
    const history = useHistory();
    let user = false;
    if(user = Cookies.get("user")){
        history.push('/Homepage');
        setAuthenticated(true);
    }else{
        history.push('/');
    }
}

然后我像这样Login.js使用它来调用它useEffect

import {ReadCookie} from './ReadCookie' 

useEffect(() => {
    ReadCookie()
},[]);

当我运行它时,它会在我的网页中显示如下错误

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
4

1 回答 1

0

You cannot call a hook from outside the scope of a React function. You could use a custom hook that reads your cookie data.

function useCookie(cookieName) {
   const [cookieValue, setCookValue] = React.useState(null)

   React.useEffect(() => {
       setCookieValue(ReadCookie())
   }, [])

   return cookieValue;
}

Login.js

function Login() {
   const cookieValue = useCookie('myCookieName');
   // here you can get cookieValue.
}

于 2020-09-07T08:04:42.510 回答