Mar*_*röm 5 reactjs react-hooks
如何等到上下文值被设置?
我有一个问题,我无法从我的上下文中获取值,所以当我需要它时,我总是得到初始值"". 所以现在useEffect我的组件中有一个,
useEffect(() => {
if (posContext.activePaymentTabId) {
console.log("poscontext i useeffect", posContext); <-- can see my value here now
// handlePaymentResponse(true, "GODKÄNT");
}
}, [posContext.activePaymentTabId]);
Run Code Online (Sandbox Code Playgroud)
我在这个函数中设置了我的值:
const makeCardPayment = async () => {
posContext.handleSetActivePaymentTabId(); // <-- Here I set my value that I need later
try {
const res = await functionA();
return functionB(res.foo);
} catch (error) {}
};
Run Code Online (Sandbox Code Playgroud)
但是在functionB需要我的价值的地方:
const functionB = (foo) => {
if (foo) {
setTimeout(() => {
console.log("calling...", posContext); // <-- Now my value is back to it's initial
}, 3500);
}
};
Run Code Online (Sandbox Code Playgroud)
那么,当我想直接从我的上下文访问我的值时,我还有哪些其他选择?
由于上下文值更改仅反映在初始渲染上,因此您可以将回调函数传递给 setter,该函数返回更新的值并将上下文值传递给functionB.
const makeCardPayment = () => {
posContext.handleSetActivePaymentTabId(async function(updatedContext) {
try {
const res = await functionA();
return functionB(res.foo, posContext);
} catch (error) {
}
});
};
Run Code Online (Sandbox Code Playgroud)
const functionB = (foo, posContext) => {
if (foo) {
setTimeout(() => {
console.log("calling...", posContext); // <-- Now my value is back to it's initial
}, 3500);
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4475 次 |
| 最近记录: |