我正在构建React-Redux应用程序,该应用程序必须从头开始从api加载列表。到目前为止,我已经能够使它使用硬编码列表来初始化状态:
reducers/Catalogs.js
import {
GET_CATALOGS,
SHOW_MESSAGE,
HIDE_MESSAGE,
GET_CATALOGS_SUCCESS
} from 'constants/ActionTypes';
const INIT_STATE = {
loader: false,
alertMessage: '',
showMessage: false,
catalogsList: ['uno', 'dos'] /// Hard coded initialization that must be from an api
};
export default (state=INIT_STATE, action) => {
switch (action.type) {
case GET_CATALOGS_SUCCESS: {
return {
...state,
loader: false,
catalogsList: action.payload
}
}
case SHOW_MESSAGE: {
return {
...state,
alertMessage: action.payload,
showMessage: true,
loader: false
}
}
case HIDE_MESSAGE: {
return {
...state,
alertMessage: '',
showMessage: false,
loader: false
}
}
case GET_CATALOGS: {
return {
...state
}
}
default:
return state;
}
}
我从阅读物中知道,reduce不应进行异步调用或调度操作,因此,我正在使用redux-sagas来管理异步调用。
sagas/Catalogs.js
import {all, call, fork, put, takeEvery} from "redux-saga/effects";
import {catalogs} from 'backend/Catalogs';
import {GET_CATALOGS} from "constants/ActionTypes";
import {getCatalogs, getCatalogsSuccess, showCatalogsMessage} from 'actions/Catalogs';
const getCatalogsRequest = async (group) =>
await catalogs.getCatalogs(group)
.then(catalogsList => catalogsList)
.catch(error => error);
function* getCatalogsListFromRequest({payload}) {
const {group} = payload;
try {
const catalogsList = yield call(getCatalogsRequest, group);
if (catalogsList.message) {
yield put(showCatalogsMessage(catalogsList.Message));
} else {
yield put(getCatalogsSuccess(catalogsList))
}
} catch (error) {
yield put(showCatalogsMessage(error));
}
}
export function* getCatalogsList() {
yield takeEvery(GET_CATALOGS, getCatalogsListFromRequest);
}
export default function* rootSaga() {
yield all([
fork(getCatalogsList)
]);
}
问题是我不知道如何使用它来初始化状态,因为这样的初始化不是动作的一部分。
基本上,您需要为主要componentDidMount()
组件创建App
并在其内部分派GET_CATALOGS
操作,这应在挂载应用程序(初始化)和更新存储时请求数据。