Reactjs 处理App.js组件中的React上下文-只能在函数体内部调用错误挂钩 下面是App.js文件,错误='Hooks只能在函数组件的主体内调用'comes'。 你能不能请任何人告诉我是什么问题,并给我解决方案。 下面是App.js文件,错误='Hooks只能在函数组件的主体内调用'comes'。 你能不能请任何人告诉我是什么问题,并给我解决方案。 import React,{useState,useContext,createContext}来自“React” 从“react router dom”导入{BrowserRouter,Route,Switch,NavLink}; 导入“/App.css”; 从“../src/routes”导入{routes}; 导入SystemService,{}来自“./shared/system_service”; export const AuthContext=React.createContext(); 常量初始状态={ I认证:错误, 用户:null, 令牌:null, }; const reducer=(状态、操作)=>{ 开关(动作类型){ 案例“登录”: setItem(“user”,JSON.stringify(action.payload.user)); setItem(“token”,JSON.stringify(action.payload.token)); 返回{ ……国家, 我证实:是的, 用户:action.payload.user, 令牌:action.payload.token }; 案例“注销”: localStorage.clear(); 返回{ ……国家, I认证:错误, 用户:空 }; 违约: 返回状态; } }; const[state,dispatch]=React.useReducer(reducer,initialState); React.useffect(()=>{ const user=JSON.parse(localStorage.getItem('user')| | null) const token=JSON.parse(localStorage.getItem('token')| | null) if(用户和令牌){ 派遣({ 键入:“登录”, 有效载荷:{ 用户, 代币 } }) } }, []) 类应用程序扩展了React.Component{ 建造师(道具){ 超级(道具); this.service=新系统服务(); this.state={isloading:true,isLogin:false}; } componentDidMount(){} componentDidCatch(){} componentDidUpdate(){} 设置值=()=>{ console.log('setvalue'); //this.setState({isloading:false}); this.context.name='test..'; 这个.forceUpdate(); } render(){ console.log('render'); var isLoggedIn=localStorage.getItem('isLogin'); console.log(this.service.Account); 返回( 您好,{this.context.name}{state.isAuthenticated} {伊斯洛格丁? 家 : 登录 登记册 试验 } {/*主页 登录 寄存器*/} {/*子页*/} {/*未找到*/} {routes.map(r=>)} ); } } 导出默认应用程序;

Reactjs 处理App.js组件中的React上下文-只能在函数体内部调用错误挂钩 下面是App.js文件,错误='Hooks只能在函数组件的主体内调用'comes'。 你能不能请任何人告诉我是什么问题,并给我解决方案。 下面是App.js文件,错误='Hooks只能在函数组件的主体内调用'comes'。 你能不能请任何人告诉我是什么问题,并给我解决方案。 import React,{useState,useContext,createContext}来自“React” 从“react router dom”导入{BrowserRouter,Route,Switch,NavLink}; 导入“/App.css”; 从“../src/routes”导入{routes}; 导入SystemService,{}来自“./shared/system_service”; export const AuthContext=React.createContext(); 常量初始状态={ I认证:错误, 用户:null, 令牌:null, }; const reducer=(状态、操作)=>{ 开关(动作类型){ 案例“登录”: setItem(“user”,JSON.stringify(action.payload.user)); setItem(“token”,JSON.stringify(action.payload.token)); 返回{ ……国家, 我证实:是的, 用户:action.payload.user, 令牌:action.payload.token }; 案例“注销”: localStorage.clear(); 返回{ ……国家, I认证:错误, 用户:空 }; 违约: 返回状态; } }; const[state,dispatch]=React.useReducer(reducer,initialState); React.useffect(()=>{ const user=JSON.parse(localStorage.getItem('user')| | null) const token=JSON.parse(localStorage.getItem('token')| | null) if(用户和令牌){ 派遣({ 键入:“登录”, 有效载荷:{ 用户, 代币 } }) } }, []) 类应用程序扩展了React.Component{ 建造师(道具){ 超级(道具); this.service=新系统服务(); this.state={isloading:true,isLogin:false}; } componentDidMount(){} componentDidCatch(){} componentDidUpdate(){} 设置值=()=>{ console.log('setvalue'); //this.setState({isloading:false}); this.context.name='test..'; 这个.forceUpdate(); } render(){ console.log('render'); var isLoggedIn=localStorage.getItem('isLogin'); console.log(this.service.Account); 返回( 您好,{this.context.name}{state.isAuthenticated} {伊斯洛格丁? 家 : 登录 登记册 试验 } {/*主页 登录 寄存器*/} {/*子页*/} {/*未找到*/} {routes.map(r=>)} ); } } 导出默认应用程序;,reactjs,react-hooks,react-context,Reactjs,React Hooks,React Context,您的应用程序组件是类组件,挂钩只能在功能组件中使用 此外,不能在文件范围外定义挂钩 将应用程序组件转换为功能组件,如下所示 export const AuthContext=React.createContext(); 常量初始状态={ I认证:错误, 用户:null, 令牌:null, }; const reducer=(状态、操作)=>{ 开关(动作类型){ 案例“登录”: setItem(“user”,JSON.stringify(action.payload.user)); setIte

您的
应用程序
组件是类组件,挂钩只能在
功能组件中使用

此外,不能在文件范围外定义挂钩

将应用程序组件转换为功能组件,如下所示

export const AuthContext=React.createContext();
常量初始状态={
I认证:错误,
用户:null,
令牌:null,
};
const reducer=(状态、操作)=>{
开关(动作类型){
案例“登录”:
setItem(“user”,JSON.stringify(action.payload.user));
setItem(“token”,JSON.stringify(action.payload.token));
返回{
……国家,
我证实:是的,
用户:action.payload.user,
令牌:action.payload.token
};
案例“注销”:
localStorage.clear();
返回{
……国家,
I认证:错误,
用户:空
};
违约:
返回状态;
}
};
const AuthProvider=(道具)=>{
const service=useRef(新系统服务());
this.state={isloading:true,isLogin:false};
}
const[state,dispatch]=React.useReducer(reducer,initialState);
React.useffect(()=>{
const user=JSON.parse(localStorage.getItem('user')| | null)
const token=JSON.parse(localStorage.getItem('token')| | null)
if(用户和令牌){
派遣({
键入:“登录”,
有效载荷:{
用户,
代币
}
})
}
}, []);
常量设置值=()=>{
console.log('setvalue');
//this.setState({isloading:false});
this.context.name='test..';
这个.forceUpdate();
}
console.log('render');
var isLoggedIn=localStorage.getItem('isLogin');
console.log(service.Account);
返回(
{儿童}
);
}
常数
below is the App.js file and Error = 'Hooks can only be called inside the body of a function component' comes.
can you please anyone let me know what is the problem and give me the solution.
below is the App.js file and Error = 'Hooks can only be called inside the body of a function component' comes.
can you please anyone let me know what is the problem and give me the solution.
import React, { useState, useContext, createContext } from 'react'
import { BrowserRouter, Route, Switch, NavLink } from "react-router-dom";
import './App.css';
import { routes } from '../src/routes';
import SystemService, { } from './shared/system_service';

export const AuthContext = React.createContext();
const initialState = {
    isAuthenticated: false,
    user: null,
    token: null,
};
const reducer = (state, action) => {
    switch (action.type) {
        case "LOGIN":
            localStorage.setItem("user", JSON.stringify(action.payload.user));
            localStorage.setItem("token", JSON.stringify(action.payload.token));
            return {
                ...state,
                isAuthenticated: true,
                user: action.payload.user,
                token: action.payload.token
            };
        case "LOGOUT":
            localStorage.clear();
            return {
                ...state,
                isAuthenticated: false,
                user: null
            };
        default:
            return state;
    }
};
const [state, dispatch] = React.useReducer(reducer, initialState);
React.useEffect(() => {
    const user = JSON.parse(localStorage.getItem('user') || null)
    const token = JSON.parse(localStorage.getItem('token') || null)

    if (user && token) {
        dispatch({
            type: 'LOGIN',
            payload: {
                user,
                token
            }
        })
    }
}, [])

class App extends React.Component {
    constructor(props) {
        super(props);
        this.service = new SystemService();
        this.state = { isloading: true, isLogin: false };
    }
    componentDidMount() { }
    componentDidCatch() { }
    componentDidUpdate() { }

    setvalue = () => {
        console.log('setvalue');
        //this.setState({ isloading: false });
        this.context.name = 'test..';
        this.forceUpdate();
    }


    render() {
        console.log('render');
        var isLoggedIn = localStorage.getItem('isLogin');
        console.log(this.service.Account);
        return (
            <AuthContext.Provider value={{ state, dispatch }}>
                <div className="jumbotron">
                    <div className="container">
                        <div className="col-sm-8 col-sm-offset-2 {process.env.REACT_APP_NOT_SECRET_CODE}">
                            <BrowserRouter>
                                <div>
                                    <div>Hello, {this.context.name} {state.isAuthenticated}</div>
                                    {isLoggedIn ?
                                        <ul>
                                            <li><NavLink id="home" activeClassName="active" to="/">Home</NavLink></li>
                                        </ul>
                                        :
                                        <ul>
                                            <li><NavLink exact activeClassName="active {isLogin}" to="/login">Login</NavLink></li>
                                            <li><NavLink activeClassName="active" to="/register">Register</NavLink></li>
                                            <li><a onClick={this.setvalue}>test</a></li>
                                        </ul>
                                    }
                                    {/*<li><NavLink id="home" activeClassName="active" to="/home">Home</NavLink></li>
                                    <li><NavLink exact activeClassName="active" to="/">Login</NavLink></li>
                                    <li><NavLink activeClassName="active" to="/register">Register</NavLink></li>*/}

                                    {/*<li><NavLink activeClassName="active" to="/home/subpage">Sub Page</NavLink></li>*/}
                                    {/*<li><NavLink activeClassName="active" to="/test">Not Found</NavLink></li>*/}
                                    <Switch>
                                        {routes.map(r => <Route key={r.path} path={r.path} exact={r.exact} component={r.component} name={r.name} />)}
                                    </Switch>
                                </div>
                            </BrowserRouter>
                        </div>
                    </div>
                </div>
            </AuthContext.Provider>
        );
    }
}

export default App;