箭头功能只能访问useReducer创建的初始状态,而不能访问更新后的状态

时间:2019-07-30 20:10:22

标签: javascript reactjs react-hooks

我正在尝试从功能组件中箭头功能内部的useReducer访问更新后的状态。但是,当我调用状态时,我只会得到初始状态对象。

减速器功能

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
    }
}

反应成分

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>
    )
}

可以在这样的api请求中使用:

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)
    }
}

我希望在start和end函数中能够看到更新的状态,但实际上我看到的是初始状态{}

1 个答案:

答案 0 :(得分:0)

要更改state,您需要dispatch进行操作。可以通过单击按钮或完全其他方式来完成。您应该按照以下内容更新start函数

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

  dispatch(action);
}

dispatch(action)将导致对渲染状态的更新。