为什么使用 dispatch 在 action 中调用函数?
Why use dispatch to call a function in actions?
在我的 redux actions.js 文件中,我有以下两个函数 ::-
export const init = () => async dispatch => {
dispatch({ type: TYPES.SET_LOADING });
await dispatch(getConfig());
await dispatch(getGenres());
dispatch({ type: TYPES.REMOVE_LOADING });
}
export const getConfig = () => async dispatch => {
const res = await axios.get('https://api.lala.org/3/configuration?api_key=370');
dispatch({
type : TYPES.GET_CONFIG,
payload : res.data
});
}
我只是对 await dispatch(getConfig());
的用途感到困惑?
我明白什么时候使用 dispatch 来发送 action
和 payload
,但是为什么要使用 dispatch 来调用函数?是因为 dispatch 是异步的,我们需要使用 await 吗?
通常你必须调度一个动作,它只是一个具有类型的对象(例如 dispatch({ type: TYPES.SET_LOADING });
)。但是,使用 redux-thunk 作为中间件,您还可以将异步函数与 redux 一起使用,例如用于获取数据。因此,您将异步函数调用作为分派的参数传递 (await dispatch(getConfig());
)。异步函数需要 return 另一个函数,该函数现在将调度函数作为参数 (const getConfig = () => async dispatch => {...}
.
在该异步函数中,您随后可以分派操作。
在我的 redux actions.js 文件中,我有以下两个函数 ::-
export const init = () => async dispatch => {
dispatch({ type: TYPES.SET_LOADING });
await dispatch(getConfig());
await dispatch(getGenres());
dispatch({ type: TYPES.REMOVE_LOADING });
}
export const getConfig = () => async dispatch => {
const res = await axios.get('https://api.lala.org/3/configuration?api_key=370');
dispatch({
type : TYPES.GET_CONFIG,
payload : res.data
});
}
我只是对 await dispatch(getConfig());
的用途感到困惑?
我明白什么时候使用 dispatch 来发送 action
和 payload
,但是为什么要使用 dispatch 来调用函数?是因为 dispatch 是异步的,我们需要使用 await 吗?
通常你必须调度一个动作,它只是一个具有类型的对象(例如 dispatch({ type: TYPES.SET_LOADING });
)。但是,使用 redux-thunk 作为中间件,您还可以将异步函数与 redux 一起使用,例如用于获取数据。因此,您将异步函数调用作为分派的参数传递 (await dispatch(getConfig());
)。异步函数需要 return 另一个函数,该函数现在将调度函数作为参数 (const getConfig = () => async dispatch => {...}
.
在该异步函数中,您随后可以分派操作。