1

我在存在最好与组件分离的复杂业务逻辑的情况下使用 Redux-Saga。我们正在采用 RTK 查询,无法手动使用端点。是的,我知道 Redux 最佳实践文档建议尽可能使用 Thunk。

这个特定的 saga 任务示例并不能很好地使用 Redux-Saga,但肯定存在业务逻辑如此复杂/长/复杂以至于它不属于组件的情况,而我们使用的 saga 功能可以不要(优雅地)用一个简单的 Thunk 模拟。在这个例子中,我想在后端做一个简单的突变(发布请求):

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)声明没有做任何事情。

你如何在 Saga 中执行突变?

4

2 回答 2

2

它是一个动作创建者,你需要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()

至于类型:您可能需要扩展类似的类型put:(typed-redux-saga我无法测试它,所以如果您必须修复某些问题,请提交对此答案的编辑)基于https://github。 com/agiledigital/typed-redux-saga/blob/591955fa5bdd73ae6f668f27a049fde21a7ffb6f/types/index.d.ts#L175-L177https://github.com/reduxjs/redux-thunk/blob/290acf90fa5afac5b49f286bb3d8fc51aa864/src/index。 ts#L25-L27

declare module 'typed-redux-saga' {

  export function put<TReturnType>(
    thunkAction: ThunkAction<TReturnType, TState, TExtraThunkArg, TBasicAction>,
  ): SagaGenerator<TReturnType, PutEffect<TReturnType>>;

}
于 2021-08-12T16:49:27.650 回答
0

如果你想在 Redux-Saga 中使用 RTK-Query 并且对 Typescript 没有问题,你需要同时使用两者putcall然后你可以使用selectRTK-query 选择器来访问数据。

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());
于 2021-11-02T00:13:13.560 回答