反应上下文挂钩更新后如何触发功能
How trigger function after react context hook updated
我正在尝试在 React 的“上下文挂钩”更新后调用一个函数。尝试了以下代码:
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;
我正在尝试在 React 的“上下文挂钩”更新后调用一个函数。尝试了以下代码:
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;