我不太了解redux-saga如何帮助我管理副作用,需要一些解释。
这是我的情况:
我正在构建一个本机应用程序,该应用程序必须在到达第一个屏幕时触发基于位置的API请求,在获取时显示负载,并在获取时显示结果。
到目前为止,我有2个减速器:设备和餐馆
DeviceRedux.js
像这样存储位置的状态:
{
locationPermission: 'authorized', // one of 'authorized', 'denied', 'restricted' or 'undetermined'
locationActive: true, // if locations services are turned on or not
locationError: '',
lastLocation: {
lat: 12.3456,
lng: 65.4321,
date: '2019-22-01T12:30:00.000+01:00,
},
fetchingLocation: false,
}
RestaurantsRedux.js
像这样存储餐厅的状态:
{
restaurantsList: [{
name: 'Pizza for You',
id: '123-oer-432',
}, ...]
fetchingRestaurants: false,
}
还有2个sagas :
DeviceSagas.js
处理有关位置的Sagas
export function* getCurrentLocationSaga(action) {
// check locations
const locationPermission = yield call(checkLocationPermission);
// save locationPermission in redux state
yield put(DeviceRedux.setLocationPermission(locationPermission));
switch (locationPermission) {
case 'authorized'
// 1 check if location service is enabled
// 2 if enabled retrieve location and save it to redux store
// handle all other possibilities
}
}
async function checkLocationPermission() {
try {
const response = await Permissions.check('location');
return response;
} catch (error) {
console.log('ERROR while checking location permission', error);
return 'denied';
}
}
RestaurantsSagas.js
处理有关餐馆的骚货
export function* getRestaurantsByPosition(api, action) {
const {
position,
} = action;
const response = yield call(api.getRestaurantsByPostion, position);
if (response.ok) {
yield put(RestaurantsActions.restaurantsByPositionSuccess(response.data));
} else {
yield handleError(response)
}
}
我想做一个新的传奇故事,开始getCurrentLocationSaga
并等待它在新位置完成,当获得新位置后,便开始新的餐厅搜索。我该怎么办?
答案 0 :(得分:0)
您可以使用take
to pull future actions:
function* watchFetchLocationsAndRestourants(action) {
yield call(getCurrentLocationSaga, action);
// wait for: 2 if enabled retrieve location and save it to redux store
const foundLocationsAction = yield take('SAVE_LOCATIONS_TO_REDUX');
const restaurants = yield call(getRestaurantsByPosition, api, {payload: foundLocationsAction.locations, type: 'YOUR_TYPE'});
}
因此,您开始获取当前位置,并且传奇仅在分派SAVE_LOCATIONS_TO_REDUX
时继续执行。接下来,您致电餐厅搜索您所拥有的位置。