Javascript GlobalContext未在类组件中更新
我试图创建GlobalContext,但当我更新这个类内组件时,它在类组件中不起作用,它显示了Javascript GlobalContext未在类组件中更新,javascript,reactjs,context-api,Javascript,Reactjs,Context Api,我试图创建GlobalContext,但当我更新这个类内组件时,它在类组件中不起作用,它显示了globalState的值,但它没有通过setGlobalState更新globalState GlobalContext import React,{useState,ReactNode}来自“React” 常量initialMapContext:{globalState:any;setGlobalState:React.Dispatch}={ 全局状态:{}, //将更新到我们在MapProvide
globalState
的值,但它没有通过setGlobalState
更新globalState
GlobalContext
import React,{useState,ReactNode}来自“React”
常量initialMapContext:{globalState:any;setGlobalState:React.Dispatch}={
全局状态:{},
//将更新到我们在MapProvider中提供的reducer
setGlobalState:()=>{},
};
const GlobalContext=React.createContext(initialMapContext);
接口道具{children?:ReactNode;}
导出函数GlobalProvider({children}:Props){
const[globalState,setGlobalState]=useState({name:'pranjal'});
返回{children};
}
导出默认GlobalContext
我在classComponent中的代码是
staticcontexttype=GlobalContext;
getData=async()=>{
const{globalState,setGlobalState}=this.context;
console.log(globalState);//pranjal
setGlobalState({name:“请登录”});
console.log(globalState);//pranjal
//我的rest代码
}
但是setGlobalState
没有更新globalState
值
尽管它在功能组件中运行良好
Function.js
const{globalState,setGlobalState}=useContext(GlobalContext);
setGlobalState({name:'Please login'})
而不是使用静态contextType=GlobalContext代码>,我建议您使用高阶组件(HOC),它用您的GlobalContext包装组件
实施:
export function useGlobalContext() {
const context = useContext(GlobalContext)
if (context === undefined) {
throw new Error('You did something wrong')
}
return [context.globalState, context.setGlobalState]
}
GlobalContext
导出一个名为withGlobalContext的HOC方法,如下所示
export const withGlobalContext = (Component) => (props) => (
<GlobalContext.Consumer>
{({ globalState, setGlobalState }) => (
<Component
globalState={globalState}
setGlobalState={setGlobalState}
{...props}
/>
)}
</GlobalContext.Consumer>
)
此外,我更喜欢导出自定义挂钩,以便在功能组件中使用上下文,而不是使用useContext
实施:
export function useGlobalContext() {
const context = useContext(GlobalContext)
if (context === undefined) {
throw new Error('You did something wrong')
}
return [context.globalState, context.setGlobalState]
}
然后在功能组件中,按如下方式使用它:
function FunctionalComponent(){
const [globalState, setGlobalState] = useGobalContext()
return (
// Your JSX here
)
}
干杯 不能在类组件中使用挂钩。这在官方文档的几个地方都有很好的介绍,例如,@JaredSmith您可能是对的,但我怀疑它为什么在渲染内部工作?您说的“它在渲染内部工作”是什么意思?@JaredSmith我的意思是,当我试图在渲染函数外部更新globalState时,它没有工作。但是在render(){}
内部,它工作得很好