状态未反映在箭头功能中?

时间:2020-10-07 18:46:13

标签: javascript reactjs

类似的问题发布在Arrow functions only have access to initial state created by useReducer, not updated state上,但尚未解决。

状态(useReducer)未反映在箭头功能中。

一个简单的例子: 反应组件

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 个答案:

答案 0 :(得分:0)

您在组件安装时将回调传递给useEffect,该回调在state{visitor: false}上具有closure

// Closure on `state = {visitor: false}` passed to useEffect
useEffect(() => {
  msg();
}, [])