![](/img/trans.png)
[英]How to keep updated react context value inside a callback in a custom hook
[英]How trigger function after react context hook updated
在 React 的“上下文挂钩”更新后,我试图调用 function。 尝试了以下代码:
const MyComponent = () => {
[context] = useContext(MyContext);
function updateContext():void {
context = "someNewContext";
}
function anotherFunction():void {
console.log("success!");
}
useEffect(() => {
anotherFunction();
}, [context]);
return (
<button onClick={updateContext}>update</button>
);
}
export default MyComponent;
现在我明白出了什么问题......首先我需要一个带有useState
的包装器,如下所示:
const App = () => {
const [context, setContext] = useState("initial value");
const value = { context, setContext };
return (
<MyContext.Provider value={value}>
<MyComponent />
</MyContext.Provider>
);
};
然后在组件上:
const MyComponent = () => {
{context, setContext} = useContext(MyContext);
function updateContext():void {
setContext("Some new context");
}
function anotherFunction():void {
console.log("success!");
}
useEffect(() => {
anotherFunction();
}, [context]);
return (
<button onClick={() => {updateContext()}}>update</button>
);
}
export default MyComponent;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.