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
}
}
慕田峪7331174
vue中ES6的箭头函数问题
箭头函数的问题
箭头没反应
箭头函数的问题
相关分类