在复杂的业务逻辑与组件分离的情况下,我使用Redux。我们采用RTK查询,无法手动使用端点。是的,我知道Redux最佳实践文档建议尽可能使用Thunk。
这个特殊的saga任务示例对于使用Redux并不是一个很好的例子,但是在某些情况下,业务逻辑是如此复杂,以至于它不属于组件,而且我们使用的saga功能不能(优雅地)被简单的Thunk模仿。在这个例子中,我想在后端做一个简单的变异(post请求):
export function* addNewCustomerTask(action: ReturnType<typeof addNewCustomer>) {
const { name, industry, defaultIdentifierObfuscationLevel } = action.payload
if (!name) {
yield put(setToast({ text: 'Name can not be empty', style: ToastStyle.Error }))
}
else if (!industry) {
yield put(setToast({ text: 'Industry can not be empty', style: ToastStyle.Error }))
}
else if (!defaultIdentifierObfuscationLevel) {
yield put(setToast({ text: 'Default identifier obfuscation level can not be empty', style: ToastStyle.Error }))
}
else {
try {
yield call(authApiEndpoints.addCustomer.initiate, action.payload)
}
catch {
console.error('Error')
}
}
}
yield call(authApiEndpoints.addCustomer.initiate, action.payload)
语句什么也不做。
你是如何在传奇中进行突变的?
发布于 2021-08-12 08:49:27
它是一个动作创建者,您需要put
它的执行结果。
// start it
const promise = yield put(authApiEndpoints.addCustomer.initiate(action.payload))
// wait until finished
yield promise;
// do something with it
// unsubscribe data - will be removed from store.
promise.unsubscribe()
至于类型:您可能需要扩展typed-redux-saga
的typed-redux-saga
类型,比如:(我无法测试它,所以如果您必须修改某个内容,请提交一个对这个答案的编辑),基于https://github.com/agiledigital/typed-redux-saga/blob/591955fa5bdd73ae6f668f27a049fde21a7ffb6f/types/index.d.ts#L175-L177和https://github.com/reduxjs/redux-thunk/blob/290acf90fa5afac5b49f286bb3d8fc51aa864ed3/src/index.d.ts#L25-L27
declare module 'typed-redux-saga' {
export function put<TReturnType>(
thunkAction: ThunkAction<TReturnType, TState, TExtraThunkArg, TBasicAction>,
): SagaGenerator<TReturnType, PutEffect<TReturnType>>;
}
发布于 2021-11-01 16:13:13
如果您想在Redux中使用RTK-Query,并且对类型记录没有问题,您需要同时使用put
和call
,那么您可以使用select
和RTK查询选择器来访问数据。
const promise = yield put(
yield call(authApiEndpoints.addCustomer.initiate, action.payload)
);
// You need to wait for the query to be done
yield promise
const { data } = yield select(authApiEndpoints.addCustomer.select());
https://stackoverflow.com/questions/68761222
复制