我想在 React + Redux 中构建一个函数,当用户单击按钮时,调用 API 并将数据加载到存储中,然后在页面上显示数据。
我想使用该redux-actions
框架:https ://redux-actions.js.org/但我对我见过的不同示例感到有些困惑。
在某些示例中,我看到以下内容:
export const GET_USER_DATA = 'GET_USER_DATA';
export const getUserData = createAction(
GET_USER_DATA,
async () => {
try {
return await getUserInfo(config);
} catch (error) {
console.log("Error occurred");
}
},
);
然后我看到了其他使用dispatch
这样的示例(取自:https ://codeburst.io/redux-actions-through-example-part-3-91dc41ebe4be ):
const fetchPhraseRequest = createAction('PHRASE_FETCH_REQUEST');
const fetchPhraseResponse = createAction('PHRASE_FETCH_RESPONSE');
export const clearPhrase = createAction('PHRASE_CLEAR');
export const fetchPhrase = () => (dispatch) => {
dispatch(fetchPhraseRequest());
fromAPI.getPhrase()
.then((value) => {
dispatch(fetchPhraseResponse(value));
})
.catch((err) => {
dispatch(fetchPhraseResponse(err));
});
};
我是 React 和 Redux 的新手,我试图了解你为什么/什么时候会做其中之一。
我对第一个示例有一个问题: - 如果不调用dispatch
,reducer 是否能够执行此操作?如果是这样,这如何在不调用调度的情况下工作?