问题
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