Arrow functions only have access to initial state created by useReducer, not updated state

删除回忆录丶 提交于 2021-01-29 11:14:46

问题


I am trying to access the updated state from useReducer inside of an arrow function in a functional component. However, when I call the state, I'm only getting the initial state object.

The reducer function

const reducer = (state, action) => {
    switch (action.type) {
        case 'UPDATE':
            return {
                ...state,
                [action.progress.request]: action.progress
            }

        case 'REMOVE':
            const { [action.progress.request]: value, ...rest } = state
            return rest

        default:
            return state
    }
}

The react component

const ProgressProvider = ({ children }: Props) => {
    const [state, dispatch] = useReducer(reducer, {})

    const start = (request) => {
        console.log(state) // expected to see updated state, but instead see initial value
        // ... do more things
    }


    const end = (request) => {
        console.log(state)
        // ...do more things
    }

    return (
        <ProgressContext.Provider value={{ state, start, end }}>
            {children}

        </ProgressContext.Provider>
    )
}

could be used in an api request like this:

const progress = useContext(ProgressContext)

const getData = async params => {
    const url = '/my/endpoint'
    progress.start(url)
    try {
        await axios.get(url, { params })
    } catch (error) {
        console.error(error)
    } finally {
        progress.end(request)
    }
}

I expect in the start and end functions to be able to see an updated state, but I actually see the initial state {}


回答1:


In order for state to change, you need to dispatch an action. This can either be done via a click of a button or something else entirely. You should update your start function to be along the lines of the following

const start = request => {
  const action = {
    type: 'UPDATE',
    request
  };

  dispatch(action);
}

The dispatch(action) will cause an update to the state that will be available on render.



来源:https://stackoverflow.com/questions/57279320/arrow-functions-only-have-access-to-initial-state-created-by-usereducer-not-upd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!