Javascript 在 redux-saga 中获取状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38405700/
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
getState in redux-saga?
提问by Andy Ray
I have a store with a list of items. When my app first loads, I need to deserialize the items, as in create some in-memory objects based on the items. The items are stored in my redux store and handled by an itemsReducer
.
我有一个商店,里面有商品清单。当我的应用程序第一次加载时,我需要反序列化这些项目,就像基于这些项目创建一些内存中的对象一样。这些项目存储在我的 redux 存储中并由itemsReducer
.
I'm trying to use redux-sagato handle the deserialization, as a side effect. On first page load, I dispatch an action:
作为副作用,我正在尝试使用redux-saga来处理反序列化。在第一页加载时,我调度一个动作:
dispatch( deserializeItems() );
My saga is set up simply:
我的传奇设置很简单:
function* deserialize( action ) {
// How to getState here??
yield put({ type: 'DESERISLIZE_COMPLETE' });
}
function* mySaga() {
yield* takeEvery( 'DESERIALIZE', deserialize );
}
In my deserialize saga, where I want to handle the side effect of creating in-memory versions of my items, I need to read the existing data from the store. I'm not sure how to do that here, or if that's a pattern I should even be attempting with redux-saga.
在我的反序列化传奇中,我想处理创建项目的内存版本的副作用,我需要从存储中读取现有数据。我不知道如何在这里做到这一点,或者如果这是我什至应该尝试使用 redux-saga 的模式。
回答by Kokovin Vladislav
you can use select effect
您可以使用选择效果
import {select, ...} from 'redux-saga/effects'
function* deserialize( action ) {
const state = yield select();
....
yield put({ type: 'DESERIALIZE_COMPLETE' });
}
also you can use it with selectors
您也可以将它与选择器一起使用
const getItems = state => state.items;
function* deserialize( action ) {
const items = yield select(getItems);
....
yield put({ type: 'DESERIALIZE_COMPLETE' });
}
回答by Alex Shwarc
Select effect does not help us if we in a callback functions, when code flow is not handled by Saga. In this case just pass dispatch
and getState
to root saga:
如果我们在回调函数中,当 Saga 不处理代码流时,选择效果对我们没有帮助。在这种情况下,只需传递dispatch
和getState
root saga:
store.runSaga(rootSaga, store.dispatch, store.getState)
And the pass parameters to child sagas
和传递参数给子传奇
export default function* root(dispatch, getState) {
yield all([
fork(loginFlow, dispatch, getState),
])
}
export default function* root(dispatch, getState) {
yield all([
fork(loginFlow, dispatch, getState),
])
}
And then in watch methods
然后在 watch 方法中
export default function* watchSomething(dispatch, getState)
...
export default function* watchSomething(dispatch, getState)
...