[英]How to get the new state with Redux-Saga?
我正在尝试获取getCart()
生成器函数返回给我的新状态,但是该状态将“延迟”。
我需要的状态只有在第二次单击按钮后才能出现。
注意:我强制执行的控制台上的错误是一种措施。
import { call, put, select, all, takeLatest } from 'redux-saga/effects';
import { TYPES } from './reducer';
import { getCart, getCartSuccess, getCartFail } from './actions';
import API from 'services/JsonServerAPI';
export function* getCartList() {
try {
const response = yield call(API.get, '/2cart');
yield put(getCartSuccess(response.data));
} catch (error) {
yield put(
getCartFail(error.response ? error.response.statusText : error.message)
);
}
}
export function* addToCart({ id }) {
yield put(getCart());
yield select(({ CartReducer }) => {
console.log(CartReducer);
});
console.log(id);
}
// prettier-ignore
export default all([
takeLatest(TYPES.GET, getCartList),
takeLatest(TYPES.ADD, addToCart)
]);
由于getCartList
执行异步操作,因此您需要某种方式来等待在addToCart
完成操作之后再进行记录。
一种选择是直接从addToCart
getCartList
调用getCartList
而不调度Redux操作-如果您有依赖TYPES.GET
其他中间件,则这可能不是TYPES.GET
。
export function* addToCart({ id }) {
// call the `getCartList` saga directly and wait for it to finish before continuing
yield call(getCartList);
yield select(({ CartReducer }) => {
console.log(CartReducer);
});
console.log(id);
}
另一种选择是take
的一次,将被分派的操作列表上getCartList
传奇完成:
export function* addToCart({ id }) {
yield put(getCart());
// wait until one of the success or failure action is dispatched, sub with the proper types
yield take([TYPES.GET_SUCCESS, TYPES.GET_FAILURE]);
yield select(({ CartReducer }) => {
console.log(CartReducer);
});
console.log(id);
}
这也有一些潜在的折衷-您将需要确保take
的动作列表与getCartList
可以put
所有可能的结束类型保持最新,并且您需要确保继续使用takeLatest
(vs takeEvery
)来触发addToCart
因此,您最终不会遇到可能满足take
子句的多个并发sagas。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.