redux-saga: eventChannel and listener which react callback return

守給你的承諾、 提交于 2021-01-28 15:31:12

问题


In react-native backhandler listener react to callback function and act appropriately.

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);
    }
}

回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/53920597/redux-saga-eventchannel-and-listener-which-react-callback-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!