如何从 redux-saga 函数中的状态/存储中获取某些东西?

How to get something from the state / store inside a redux-saga function?

如何在 saga 函数中访问 redux 状态?

简答:

import { select } from 'redux-saga/effects';
...
let data = yield select(stateSelectorFunction);

这就是 "selector" 函数的用途。你将整个状态树传递给他们,他们 return 状态的一部分。调用选择器的代码不需要知道数据所在状态的 位置 ,只需知道它是 returned。有关示例,请参阅 http://redux.js.org/docs/recipes/ComputingDerivedData.html

在 saga 中,select() API 可用于执行选择器。

正如@markerikson 已经说过的那样,redux-saga 公开了一个非常有用的 API select() 来调用状态上的 selector 以获得它的某些部分在传奇。

对于您的示例,一个简单的实现可以是:

/*
 * Selector. The query depends by the state shape
 */
export const getProject = (state) => state.project

// Saga
export function* saveProjectTask() {
  while(true) {
    yield take(SAVE_PROJECT);
    let project = yield select(getProject); // <-- get the project
    yield call(fetch, '/api/project', { body: project, method: 'PUT' });
    yield put({type: SAVE_PROJECT_SUCCESS});
  }
}

除了建议的 doc by @markerikson, there is a very good video tutorial by D. Abramov which explains how to use selectors with Redux. Check also this Twitter 上有趣的话题。

我使用 eventChannel 从生成器函数中的回调调度动作

import {eventChannel} from 'redux-saga';
import {call, take} from 'redux-saga/effects';

function createEventChannel(setEmitter) {
    return eventChannel(emitter => {
        setEmitter(emitter)
        return () => {

        }
      }
    )
}

function* YourSaga(){
    let emitter;
    const internalEvents = yield call(createEventChannel, em => emitter = em)

    const scopedCallback = () => {
        emitter({type, payload})
    }

    while(true){
        const action = yield take(internalEvents)
        yield put(action)
    }
}