每次我从以下代码行运行 yarn start 时,都会const context = useContext(GlobalContext);
遇到“错误:无效的钩子调用。只能在函数组件的主体内部调用钩子”。我该如何解决这个问题,这让我很精神。这是显示错误、依赖项和我的代码的屏幕截图
这是我的 globalState 的代码,如果这是导致它的原因
import React, { createContext, useReducer } from "react";
import AppReducer from './AppReducer';
// initial state
const initialState = {
healthData:
{ age: "38", gender: "male", goal: "Lose", height: "180.34", weight: 80 }
}
export const GlobalContext = createContext(initialState);
// provider component
export const GlobalProvider = ({ children }) => {
const [state, dispatch] = useReducer(AppReducer, initialState);
return (<GlobalContext.Provider value={{
healthData: state.healthData
}}>
{children}
</GlobalContext.Provider>);
}
export default (state, action) => {
switch(action.type) {
default:
return state;
}
}
return (
<div>
<Router>
<div className='App'>
{this.state.user ? (<Nav drawerClickHandler={this.drawerToggleClickHandler} />) : (<Login_bar />)}
<SideDrawer sidedrawerClickHandler={this.sidedrawerToggleClickHandler} show={this.state.sideDrawerOpen} />
{backdrop}
<GlobalProvider>
{this.state.user ?
(< Switch >
<Route path='/settings_page' component={settings_page} exact />,
<Route path='/setup_page' component={setup_page} exact />,
<Route path='/' component={Main_page} />
</Switch>) : (<Login_page />)}
</GlobalProvider>
</div>
</Router>
</div >
);
因此,我对此进行了一些研究,显然我的 react 或 react-dom 可能不是最新的。Iv 尝试多次更新并运行 npm install。没有解决我的问题,我也几乎可以肯定我正确地调用了钩子。另一件事是我的全局状态设置正确,因为我可以在 react chrome 扩展中看到它。