[英]React Context updated state not reflecting in nested functions when using Hooks
I have displayed two buttons during my initial render of the react component.我在最初渲染反应组件时显示了两个按钮。 If i clicked on button primary.
如果我点击主要按钮。 the relevant onClick function will dispatch an event to update the reducer state and then executes the nested function which again prints state.
相关的 onClick function 将发送一个事件来更新 reducer state,然后执行嵌套的 function 再次打印 state。
The problem I am facing was the updated state is not reflecting in the nested functions.
我面临的问题是更新后的 state 没有反映在嵌套函数中。 Could you let me know what I am missing here?
你能让我知道我在这里缺少什么吗?
import React, { useEffect, useContext } from "react";
import { MainContext } from "../Main/Main";
// Main
function FirstTab() {
// // Access Context
const { mainState, mainDispatch } = useContext(MainContext);
const filterState = mainState.filter;
console.log("AppMainState->SalesTab:", filterState);
const updateFilterContext = (data) => {
console.log("Inside Filter Update:", data);
mainDispatch({ type: "UPDATE_FILTER", data: data });
};
//ss
const PrimaryClick2 = (filterState) => {
console.log("Primary Click2");
console.log("AppMainState->PrimaryClick2:", filterState);
};
const PrimaryClick1 = (filterState) => {
console.log("Primary Click1");
console.log("AppMainState->PrimaryClick1:", filterState);
PrimaryClick2(filterState);
};
const PrimaryClick = (filterState) => {
console.log("Primary Click");
console.log("AppMainState->PrimaryClick:", filterState);
updateFilterContext({ selectedValue: "NEWVALUE" });
PrimaryClick1(filterState);
};
useEffect(() => {
console.log("Step1: Generating First Tab");
}, [mainState.filter.applyFilter]);
return (
<div>
<div>
<button class="ui primary button" onClick={PrimaryClick}>
Primary
</button>
<button class="ui secondary button">Secondary</button>
</div>
</div>
);
}
export default FirstTab;
My guess is that mainDispatch
is asynchronous.我的猜测是
mainDispatch
是异步的。
You might be able to check for changes with this:您也许可以通过以下方式检查更改:
useEffect(() => {
console.log('mainState changed')
console.log(mainState.filter)
}, [mainState])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.