如何在React Native中使用Redux Saga监视网络更改

by Pritish Vaidya

通过Pritish Vaidya

如何在React Native中使用Redux Saga监视网络更改 (How to monitor network changes using Redux Saga in React Native)

为什么要使用Redux Saga监视网络更改? (Why should I use Redux Saga to monitor Network Changes?)

Redux Saga is an alternate side effect model for redux apps. It is easier to manage, execute, test and catch errors.

Redux Saga是Redux应用程序的替代 副作用模型。 它更易于管理,执行,测试和捕获错误。

Rather than implementing the logic to manage the network state in your react component, the side-effects should be handled separately. Redux Saga provides us with eventChannel as an out of the box solution for handling such cases.

与其在您的React组件中实现管理网络状态的逻辑,不如单独处理这些side-effects 。 Redux Saga为我们提供了eventChannel作为处理此类情况的现成解决方案。

什么是事件频道? (What is an Event Channel?)

Redux Saga consists of eventChannels to communicate between external events and sagas as a factory function. The events are from the event sources other than the redux store.

Redux Saga由eventChannels组成,用于在外部事件sagas之间进行通信,作为工厂功能。 这些事件来自Redux存储以外的事件源。

Here’s a basic example from the docs:

这是docs中的一个基本示例:

import { eventChannel } from 'redux-saga'

function countdown(secs) {
  return eventChannel(emitter => {
      const iv = setInterval(() => {
        secs -= 1
        if (secs > 0) {
          emitter(secs)
        } else {
          // this causes the channel to close
          emitter(END)
        }
      }, 1000);
      return () => {
        clearInterval(iv)
      }
    }
  )
}

Things to note:

注意事项:

  • The first argument of the eventChannel is a listener function.

    eventChannel的第一个参数是侦听器函数。

  • The return method is the unregister listener function.

    返回方法是注销注册侦听器函数。

Emitter initializes the listener once after which all the events from the listener are passed to the emitter function by invoking it.

发射器初始化监听器一次,之后通过调用它将来自监听器的所有事件传递给发射器函数

我应该如何使用React Native的Network(NetInfo)API连接Redux Saga的事件频道? (How should I hook up Redux Saga’s Event Channel with React Native’s Network(NetInfo) API?)

The React Native’s NetInfo isConnected API asynchronously fetches a boolean which determines whether the device is online or offline.

React Native的NetInfo isConnected API异步获取一个布尔值 ,该布尔值确定设备是online还是offline

深入研究代码 (Dive into the code)

First, we need to create a start channel method.

首先,我们需要创建一个启动通道方法。

import { NetInfo } from "react-native"
import { eventChannel} from "redux-saga"

function * startChannel() {
  const channel = eventChannel(listener => {
    const handleConnectivityChange = (isConnected) => {
      listener(isConnected);
    }
    
// Initialise the connectivity listener
    NetInfo.isConnected.addEventListener("connectionChange", handleConnectivityChange);
    
// Return the unregister event listener.
    return () =>
      NetInfo.isConnected.removeEventListener("connectionChange",    handleConnectivityChange);
  });
}

The next step is to listen for the event changes within the channel.

下一步是侦听通道内的事件更改

...

while (true) {
  const connectionInfo = yield take(channel);
}

...

The final step is to pass a custom action to the channel so that the value can be synced using your action.

最后一步是将自定义操作传递到通道,以便可以使用您的操作同步值

...
function * startChannel(syncActionName) {

...
while (true) {
  const connectionInfo = yield take(channel);
  yield put({type: syncActionName, status: connectionInfo });
}

This channel can be used in our default exported generator by using the call operation.

通过使用调用操作,可以在我们的默认导出生成器中使用此通道

export default function* netInfoSaga() {
  try {
    yield call(startChannel, 'CONNECTION_STATUS');
  } catch (e) {
    console.log(e);
  }
}

The exported generator can then be imported and used as a detached task using spawn/fork operation in our main saga.

然后,可以在我们的主要传奇中使用生成/叉操作将导出的生成器 导入并用作独立任务

用法 (Usage)

The above code has added it as a package react-native-network-status-saga to include some of the more useful and cool parameters.

上面的代码将其添加为package react-native-network-status-saga以包括一些更有用和更酷的参数。

Here are the links

这里是链接

Thanks for reading. If you liked this article, show your support by clapping this article to share with other people on Medium.

谢谢阅读。 如果您喜欢这篇文章,请拍一下这篇文章以与Medium上的其他人分享以表示支持。

More of the cool stuff can be found on my StackOverflow and GitHub profiles.

在我的StackOverflowGitHub个人资料中可以找到更多有趣的东西。

Follow me on LinkedIn, Medium, Twitter for further update new articles.

LinkedInMediumTwitter上关注我,以获取更多更新的新文章。

翻译自: https://www.freecodecamp.org/news/how-to-monitor-network-changes-using-redux-saga-in-react-native-b7b95635ef65/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值