问题描述
之前有人问过类似的问题,但答案对我没有任何帮助.
Similar questions have been asked before, but the answers have not been of any help to me.
如何获得来自 redux-saga 函数内的 state/store 的东西?
我认为我有不同的设置,因为我似乎无法从我的 saga 访问状态.
I think that I have a different setup since I cannot seem to be able to access state from my saga.
我尝试过:
const getList = store => store;
const getList = state=> state;
这些都返回 undefined
.
我的商店看起来像这样...
My store looks like this...
export default function createStoreWithMiddleware() {
const sagaMiddleware = createSagaMiddleware();
const loggerMiddleware = createLogger();
const middleware = [sagaMiddleware, loggerMiddleware];
const persistedState = localStorage.getItem('reduxState') ? JSON.parse(localStorage.getItem('reduxState')) : {};
const store = createStore(reducer, persistedState, compose(
applyMiddleware(...middleware)
));
store.subscribe(() => {
localStorage.setItem('reduxState', JSON.stringify(store.getState()));
});
sagaMiddleware.run(rootSaga);
return store;
}
我想访问我在这个传奇中的列表:
And I want to access my list in this saga:
function* selectTender(action) {
try {
const response = yield Api.getTenderById(action.payload);
yield put({type: 'SELECT_TENDER_SUCCEEDED', currentTender: response});
const list = yield select(getList);
yield put({type: 'FETCH_CHAPTERS', chaptersList: list, tenderId: response.id});
} catch (err) {
yield put({type: 'SELECT_TENDER_FAILED', message: err.message});
}
}
export function* watchSelectTender(){
yield takeEvery('SELECT_TENDER', selectTender);
}
但就像我说的,state
和 store
都是未定义的.
But like I said, both state
and store
are undefined.
那么,我如何在传奇中访问我的商店(或州)?
So, how do I access my store (or state) in the saga?
推荐答案
为此您将不得不使用选择器.我举一个简单的例子.创建文件 selectors.js
并添加您要从商店中选择的字段,如下所示.
You will have to use selectors for that. I'll give a simple example.Create a file selectors.js
and add the fields you want to select from your store, as shown below.
export const username = (state) => state.user.name;
然后在你的传奇中,将选择器导入为,
Then in your saga, import the selectors as,
import * as selectors from './selectors';
当你在你的传奇中需要 username
时,你可以简单地做,
and when you require username
in your saga, you can simply do,
import {select} from 'redux-saga/effects';
...
...
function *sampleSaga(params) {
const username = yield select(selectors.username);
}
sampleSaga
中的常量 username
现在将保存来自 state 的用户名值.
the constant username
in sampleSaga
will now hold the username value from state.
这篇关于redux saga 选择器,如何从 saga 访问状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!