Redux Saga-所有手表都需要采取派遣行动

时间:2019-07-17 06:07:23

标签: reactjs redux redux-saga saga

我声明了以下saga api。

.class {
    scrollbar-width: none;
}

当我从容器中分派动作时,两个传奇故事都触发了。但是在那我只叫getProducts。即使我确实保存了产品,也要在保存产品之前触发getProducts。

export function* watchSaveProducts() {
  yield takeLatest(ProductActionTypes.PRODUCT_SAVE_REQUEST, saveProducts);
}

export const saga = function* productSagasContainer() {
  yield all([watchGetProducts(), watchSaveProducts()]);
};

像这样的调度道具

    componentDidMount() {
    this.props.getProducts();
  }

1 个答案:

答案 0 :(得分:1)

执行此操作时将同时抛出两种方法:

export const saga = function* productSagasContainer() {
  yield all([watchGetProducts(), watchSaveProducts()]);
};

因此,两者都将始终运行。

当我使用redux和sagas时,我将解释我的结构:

  1. 首先,创建一个sagaMiddleware以将redux-store与sagas连接(摘自redux-saga documentation):
import createSagaMiddleware from 'redux-saga'
import reducer from './path/to/reducer'

export default function configureStore(initialState) {
  // Note: passing middleware as the last argument to createStore requires redux@>=3.1.0
  const sagaMiddleware = createSagaMiddleware()
  return {
    ...createStore(reducer, initialState, applyMiddleware(/* other middleware, */sagaMiddleware)),
    runSaga: sagaMiddleware.run(rootSaga)
  }
}
  1. 用Sagas定义 rootSaga,将其分为应用部分
export function* rootSaga() {
  yield all([fork(sample1Watcher), fork(sample2Watcher)]);
}
  1. 根据要分派的动作创建将在此部分中启动的 sagas集
export function* sample1Watcher() {
  yield takeLatest(ProductActionTypes.GET_PRODUCT_REQUEST, getProduct);
  yield takeLatest(ProductActionTypes.PRODUCT_SAVE_REQUEST, saveProduct);
}
  1. 定义每种方法,例如get:
function* getProduct() {
  try {
    yield put({ type: actionTypes.SET_PRODUCTS_LOADING });

    const data = yield call(products.fetchProductsAsync);

    yield put({ type: actionTypes.GET_PRODUCTS_COMPLETE, payload: data });

  } catch (e) {
    console.log("Error");
  }
}
  1. 最后,在dispatchToProps中定义 action方法,并在任何需要的地方启动
const mapDispatchToProps = (dispatch: any) => ({
  getProducts: () => dispatch(productActions.getProducts()),
  saveProduct: (ids: number[]) => dispatch(productActions.saveProduct(ids)),
});
componentDidMount() {
  this.props.getProducts();
}