问题描述
在 react-native backhandler 中,侦听器对回调函数做出反应并采取适当的行动.
In react-native backhandler listener react to callback function and act appropriately.
我需要阅读我的商店并根据它返回 true 或 false.但是我不能在普通函数中使用选择效果,也不能从watchBackButton"函数影响监听器回调函数.
I need to read my store and depending on it, return true or false.But I cant use select effect in normal function and I cant affect listener callback function from "watchBackButton" function.
export function* backButtonListen() {
return eventChannel(emitter => {
const backHandlerListener = BackHandler.addEventListener(
"hardwareBackPress",
() => {
emitter("back pressed");
}
);
return () => {
backHandlerListener.remove();
};
});
}
export function* watchBackButton() {
const chan = yield call(backButtonListen);
try {
while (true) {
let back = yield take(chan);
}
}
推荐答案
由于事件通道不是双向的,我认为没有办法使用 select 效果.
Since event channels are not bidirectional, I don't think there is a way to get some current state from saga to event channel using the
select
effect.
但是,可以直接访问商店.有多种方法可以将存储实例获取到事件通道.在此处查看我的其他答案.
However, it is possible to access the store directly. There are multiple ways to get the store instance to the event channel. See my other answer here.
使用例如您可以执行以下操作的上下文方法:
Using e.g. the context method you could do something like this:
// redux.js
...
const store = createStore(...);
sagaMiddleware.runSaga(rootSaga, {store});
// root-saga.js
export default function * rootSaga(context) {
yield setContext(context);
yield fork(watchBackButton);
}
// watch-back-button.js
export function* backButtonListen() {
const store = yield getContext('store');
return eventChannel(emitter => {
const backHandlerListener = BackHandler.addEventListener(
"hardwareBackPress",
() => {
emitter("back pressed");
return store.getState().foo === 'bar';
}
);
return () => {
backHandlerListener.remove();
};
});
}
export function* watchBackButton() {
const chan = yield call(backButtonListen);
try {
while (true) {
let back = yield take(chan);
}
}
这篇关于redux-saga:响应回调返回的事件通道和监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!