Arrow functions上发布的类似问题只能访问由 useReducer 创建的初始状态,不能访问更新状态但不能解决。状态 (useReducer) 未反映在箭头函数中。一个简单的例子:React 组件const Component = ({ children }: Props) => { const [state, dispatch] = useReducer(reducer, {visitor: false}) useEffect(() => { someObject = new Connection({ onMessage: msg onSuccess: () => dispatch({type: "Visitor", value: true}) }) return () => console.log("UNMOUNTING "); }, []); const msg = (request) => { // visitor: false console.log(state) // expected updated state, but instead see initial state, why? // ... do more things } // visitor: true console.log(state) // updated state is present here return ( <Component.Provider value={{ state }}> {children} </Component.Provider> )}减速机功能:const reducer = (state, action) => { switch (action.type) { case 'Visitor': return {...state, visitor: true} default: return state }}
1 回答
慕田峪7331174
TA贡献1828条经验 获得超13个赞
您正在将回调传递给useEffect
组件安装,此回调在value上有一个闭包。state
{visitor: false}
// Closure on `state = {visitor: false}` passed to useEffect
useEffect(() => {
msg();
}, [])
添加回答
举报
0/150
提交
取消