如何从 saga 获取 action.params

How to get action.params from saga

我正在使用 redux-saga。在代码 yield* ReduxSaga.takeEvery('MY_ACTION', updatePorts); 中,我如何访问 action 以获取其字段。

例如我有一个动作创建器:

function status(){
  type: 'MY_ACTION',
  status: true
} 

如何从我的 saga 访问 action.status?还是我只能通过 getState()select 访问数据?

const actionCreator=()=>({
  type: 'MY_ACTION',
  status:true
})

 function* updatePorts(action) {
  console.log(action.status)
}

function* watchUpdatePorts() {
  yield* takeEvery('MY_ACTION', updatePorts)
}

https://github.com/redux-saga/redux-saga/tree/master/docs/api#takeeverypattern-saga-args

const actionCreator = () => ({
  type: 'MY_ACTION',
  status: true
})

function* updatePorts() {
  while (true) {
      const { status } = take('MY_ACTION');
      // ...
  }

}

你也可以这样做。 redux-saga 文档对优点有很好的解释:

Using take has a subtle impact on how we write our code. In the case of takeEvery the invoked tasks have no control on when they'll be called. They will be invoked again and again on each matching action. They also have no control on when to stop the observation.

In the case of take the control is inverted. Instead of the actions being pushed to the handler tasks, the Saga is pulling the action by itself. It looks as if the Saga is performing a normal function call action = getNextAction() which will resolve when the action is dispatched.

在此处阅读更多内容:https://redux-saga.js.org/docs/advanced/FutureActions.html

通常你可能有一个 root saga 或 index saga 并且你可以有一个带有 yield all 的初始化生成器,如下所示:

//in your action creator
const actionCreator = () => ({
    type: 'MY_ACTION1',
    status: true
});
//in your saga file, you will receive 'action' and then you can destructure it to status if you want.
function* updateDataForAction1({ status }) {
    //use value of status 
}
//in your root saga file
export function* watchInit() {
    yield all([
        takeEvery('MY_ACTION1', updateDataForAction1),
        takeEvery('MY_ACTION2', updateDataForAction2),
        takeEvery('MY_ACTION3', updateDataForAction3),
    ]);
}