我在redux-saga应用中,我提出了api请求,并且回复很长。
我的传奇看起来像这样:
export function* fetchWeatherByCityNameSaga(action) {
try {
const response = yield call(api.getWeatherByCityName, action.payload.city);
yield put({ type: FETCH_WEATHER_SUCCESS, payload: response });
} catch (err) {
yield put({ type: FETCH_WEATHER_START, payload: err });
}
}
export function* watcherSagas() {
yield all([
yield takeLatest(FETCH_WEATHER_START, fetchWeatherByCityNameSaga),
]);
}
在有效负载中,我有这样的东西:
{…}
city: Object { id: 745042, name: "Istanbul", country: "TR", … }
cnt: 40
cod: "200"
list: Array(40) [ {…}, {…}, {…}, … ]
message: 0
现在,我要基于此响应对象创建一个新对象,并将该新对象放入商店。我不想存储无用的数据。我应该在哪里做?在fetchWeatherByCityNameSaga()中,在actionCreators中还是在组件本身中?
您应该创建一个将响应作为参数并返回仅包含所需数据的新对象的新函数。
假设您正在获得对象作为响应
例如
function transformWeatherData(response) {
// make an object with only the data you need
const data = {
cityName: response.city.name,
countryName: response.city.country,
weatherData: response.list[0].weather.main
}
return data;
}
并且在fetchWeatherByCityNameSaga中调用该函数
export function* fetchWeatherByCityNameSaga(action) {
try {
const response = yield call(api.getWeatherByCityName, action.payload.city);
// call the transform function here
const result = yield call(transformWeatherData, response);
// send the result as payload
yield put({ type: FETCH_WEATHER_SUCCESS, payload: result });
} catch (err) {
yield put({ type: FETCH_WEATHER_START, payload: err });
}
}
如果您已经提前知道响应中需要哪些字段,我只会建议您采用这种方式转换数据。如果您不知道将整个回复保存在商店中。