箭头函数只能访问由 useReducer 创建的初始状态,不能访问更新状态 [英] Arrow functions only have access to initial state created by useReducer, not updated state
问题描述
我正在尝试从功能组件中箭头函数内的 useReducer 访问更新状态.但是,当我调用状态时,我只得到初始状态对象.
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.
reducer 函数
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 请求中使用:
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 {}
推荐答案
为了让 state
改变,你需要 dispatch
一个动作.这可以通过单击按钮或完全其他方式来完成.您应该按照以下内容更新 start
函数
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);
}
dispatch(action)
将更新渲染时可用的状态.
The dispatch(action)
will cause an update to the state that will be available on render.
这篇关于箭头函数只能访问由 useReducer 创建的初始状态,不能访问更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!