在我的应用程序中,我在单击按钮时使用来自 useReducer 钩子的调度,在同一个函数中,我使用了 2 秒的 setTimeout。但是当我使用 usereducer 的调度存储数据时,我没有在 setTimeout 函数中获得更新的值。
我无法共享原始代码,但可以共享出现此问题的另一个演示应用程序的片段。
const initialData = { data: "ABC" };
function reducer(state = initialData, action) {
switch (action.type) {
case "STORE":
return {
...state,
data: action.payload
};
default:
return state;
break;
}
}
function Demo() {
const [state, dispatch] = React.useReducer(reducer, initialData);
console.log("Render : ",state.data); //Will be executed on each rendering
const handleClick = () => {
dispatch({
type: "STORE",
payload: state.data + parseInt(Math.random() * 10)
});
setTimeout(() => {
console.log("ButtonClick : ",state.data); //Will be executed after 2 seconds of dispatching.
}, 2000);
};
return <button onClick={handleClick}>{state.data}</button>;
}
ReactDOM.render(<Demo />, document.getElementById("app"));
在上面的示例中,我使用调度将数据存储在减速器中,并且我在 2 秒后在按钮单击上调用 console.log("ButtonClick") 但即使在 2 秒后,我也没有在控制台中获取更新的数据。但是在 console.log("Render") 我得到更新的数据。