1 回答

TA贡献1862条经验 获得超6个赞
state 永远不会改变该功能
该state功能永远不会改变的原因state是仅在重新渲染时才更新。因此,如果要访问,则state有两个选择:
useRef以查看的未来价值state(您必须修改减速器以使其正常工作)
const updatedState = useRef(initialState);
const reducer = (state, action) => {
let result;
// Do your switch but don't return, just modify result
updatedState.current = result;
return result;
};
return [...useReducer(reducer, initialState), updatedState];
您可以setInterval在每次状态更改后重置您的状态,以便它可以看到最新状态。但是,这意味着您的间隔可能会中断很多。
const otherFunction = useCallback(() => {
fetch('/other_path')
.then(res => {
// why is `state.stateUpdated` here still 'false'????
dispatch({ type: 'DO_SOMETHING_ELSE', res });
});
}
}, [state.stateUpdated]);
useEffect(() => {
const id = setInterval(otherFunction, 30000);
return () => clearInterval(id);
}, [otherFunction]);
添加回答
举报