反应:如何从另一个文件调用函数?

时间:2020-09-07 07:58:19

标签: reactjs

我试图将一个函数分离到另一个文件,并在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:

1 个答案:

答案 0 :(得分:0)

您不能从React函数的范围之外调用钩子。 您可以使用自定义钩子读取Cookie数据。

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.
}