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调用。这是我的假设。