Javascript 如何从 redux-saga 函数中的 state/store 获取一些东西?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37772877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get something from the state / store inside a redux-saga function?
提问by Adam Tal
How do I access the redux state inside a saga function?
如何访问 saga 函数内的 redux 状态?
Short answer:
简短的回答:
import { select } from 'redux-saga/effects';
...
let data = yield select(stateSelectorFunction);
回答by NickGnd
As @markerikson already says, redux-saga
exposes a very useful API select()
to invoke a selector
on the state for getting some part of it available inside the saga.
正如@markerikson 已经说过的那样,redux-saga
公开了一个非常有用的 APIselect()
来调用selector
状态上的a ,以便在 saga 中获取它的某些部分。
For your example a simple implementation could be:
对于您的示例,一个简单的实现可能是:
/*
* 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});
}
}
In addition to the suggested docby @markerikson, there is a very good video tutorialby D. Abramov which explains how to use selectors
with Redux. Check also thisinteresting thread on Twitter.
除了@markerikson推荐的文档外,D. Abramov还提供了一个非常好的视频教程,其中解释了如何使用selectors
Redux。在 Twitter 上也查看这个有趣的线程。
回答by markerikson
This is what "selector" functions are for. You pass them the entire state tree, and they return some piece of the state. The code that calls the selector doesn't need to know wherein the state that data was, just that it was returned. See http://redux.js.org/docs/recipes/ComputingDerivedData.htmlfor some examples.
这就是“选择器”功能的用途。你将整个状态树传递给他们,他们返回状态的一部分。调用选择的代码并不需要知道其中的状态数据,只是它返回。有关一些示例,请参阅http://redux.js.org/docs/recipes/ComputingDerivedData.html。
Within a saga, the select()
APIcan be used to execute a selector.
在 saga 中,select()
API可用于执行选择器。
回答by yardenapp
I used an eventChannel to dispatch an action from a callback within the generator function
我使用 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)
}
}