提问人:Vight 提问时间:5/16/2021 最后编辑:Lin DuVight 更新时间:5/21/2021 访问量:1062
从另一个商店切片中的一个存储切片调用一个 redux 操作
Calling one redux action from one store slice in another store slice
问:
我是 redux 的新手。在我的应用程序中,我正在使用 redux thunk 的一些异步操作。 例如,我有这个操作从 API 加载电影:
export const loadMovies = (url) => async (dispatch) => {
const response = await fetch(url);
const result = await response.json();
const { total_pages: totalPages, results: movies } = result;
dispatch(moviesLoaded(totalPages, movies));
};
我有情况L,如果没有要加载的电影(在数据库中搜索没有给我结果),所以我想将状态(它是另一个redux商店切片)更新为“没有电影”,例如。并根据该状态呈现不同的组件。
所以我的新动作是这样的:
export const loadMovies = (url) => async (dispatch) => {
const response = await fetch(url);
const result = await response.json();
if (result) {
const { total_pages: totalPages, results: movies } = result;
dispatch(moviesLoaded(totalPages, movies));
} else {
dispatch(updateStatus('no-movies')) // updateStatus is imported from another redux store slice
}
};
我想知道这样做可以吗?或者,将操作从一个商店切片导入到另一个商店切片是一种不好的做法。还有什么更好的方法来处理这种情况。
答:
2赞
Lin Du
5/20/2021
#1
您无需从其他商店切片导入操作。您可以在多个商店切片的 reducer 中处理相同的查询电影操作类型。有关详细信息,请参阅允许多个 Reducer 响应相同的操作
例如
import { createStore, applyMiddleware, combineReducers } from 'redux';
import thunk from 'redux-thunk';
const GET_MOVIES_FULFILLED = 'GET_MOVIES_FULFILLED';
function moviesLoaded(totalPages, movies) {
return {
type: GET_MOVIES_FULFILLED,
payload: {
totalPages,
movies,
},
};
}
export const loadMovies = () => async (dispatch) => {
// const response = await fetch(url);
// const result = await response.json();
// mock result
const result = { total_pages: 0, results: [] };
const { total_pages: totalPages, results: movies } = result;
dispatch(moviesLoaded(totalPages, movies));
};
const rootReducer = combineReducers({
sliceA(state = { totalPages: 0, movies: [] }, action) {
switch (action.type) {
case GET_MOVIES_FULFILLED:
return action.payload;
default:
return state;
}
},
sliceB(state = { status: '' }, action) {
switch (action.type) {
case GET_MOVIES_FULFILLED:
if (!action.payload.movies || !action.payload.movies.length) {
return {
status: 'no movies',
};
}
default:
return state;
}
},
});
const store = createStore(rootReducer, applyMiddleware(thunk));
store.dispatch(loadMovies() as any).then(() => {
console.log(store.getState());
});
输出:
{
sliceA: { totalPages: 0, movies: [] },
sliceB: { status: 'no movies' }
}
调度操作,处理它并减少。GET_MOVIES_FULFILLED
sliceA
sliceB
如果没有电影,我们将 的状态设置为 。sliceB
{status: 'no movies'}
评论