如何从 redux-saga 函数中的 state/store 获取一些东西? [英] How to get something from the state / store inside a redux-saga function?
问题描述
如何在 saga 函数中访问 redux 状态?
How do I access the redux state inside a saga function?
简答:
import { select } from 'redux-saga/effects';
...
let data = yield select(stateSelectorFunction);
推荐答案
正如@markerikson 已经说过的,redux-saga
公开了一个非常有用的 API select()
在状态上调用 selector
以获取它的某些部分在传奇中可用.
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.
对于您的示例,一个简单的实现可能是:
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});
}
}
除了@markerikson 建议的 doc 之外,还有一个非常D. Abramov 的优秀视频教程,解释了如何使用<代码>选择器代码>与 Redux.另请查看 Twitter 上的这个有趣的帖子.
In addition to the suggested doc by @markerikson, there is a very good video tutorial by D. Abramov which explains how to use selectors
with Redux. Check also this interesting thread on Twitter.
这篇关于如何从 redux-saga 函数中的 state/store 获取一些东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!