Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应:如何从另一个文件调用函数?_Reactjs - Fatal编程技术网

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

Reactjs 反应:如何从另一个文件调用函数?,reactjs,Reactjs,我尝试将一个函数分离到另一个文件,并在useffect()中调用它。这是我的密码 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 = () =>

我尝试将一个函数分离到另一个文件,并在
useffect()
中调用它。这是我的密码

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('/');
    }
}
然后我像这样使用
useffect
将其调用到
Login.js

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:
当我运行它时,它会在我的网页中显示错误,如下所示

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:

不能从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.
}


useState
useffect
是否在
useCookie
内部冗余?如果饼干基本上被退回了,那么使用它有什么意义呢?我同意你的意见。他想使用
useffect
来读取cookie函数。可能在
useffect
中的某个地方有一个API调用。这是我的假设。