如何在react-native中使用Redux来调度NetInfo连接更改操作?

rea*_*ebo 2 javascript react-native redux redux-thunk

我希望能够在我的反应本机应用程序中“持续”监视设备连接。

我已经成功使用 redux-thunk 和 redux 了。

其实我可以做到这一点

import { NetInfo } from 'react-native';

import {
    CONNECTION_CHECKING,
    CONNECTION_AVAILABLE,
    CONNECTION_UNAVAILABLE, 
} from './types';


export const connectionChecking = () => {
    return (dispatch) => {

        dispatch ({
            type: CONNECTION_CHECKING
        });

        NetInfo.getConnectionInfo()
            .then((connectionInfo) => {

                console.log('Connection info: ', connectionInfo);
                switch (connectionInfo.type) {
                    case 'cellular':
                        dispatch ({
                            type: CONNECTION_AVAILABLE,
                            payload: connectionInfo.type
                        });
                        break;
                    case 'wifi':
                        dispatch ({
                            type: CONNECTION_AVAILABLE,
                            payload: connectionInfo.type
                        });
                        break;
                    default:
                        dispatch ({
                            type: CONNECTION_UNAVAILABLE,
                        });
                }
            })
            .catch((error) => console.warn(error));

    };
};
Run Code Online (Sandbox Code Playgroud)

但是,我不知道如何在连接更改时调度新操作。

从反应本机文档中我看到了这一点:

NetInfo.addEventListener(
  'connectionChange',
  handleConnectivityChange
);
Run Code Online (Sandbox Code Playgroud)

但是...如何在事件侦听器内调度操作?

我尝试将其添加到同一个操作文件中

NetInfo.addEventListener(
    'connectionChange', (connectionInfo)  => {
        return (dispatch) => {

            console.log('Connection info changed ', connectionInfo);
            switch (connectionInfo.type) {
                case 'cellular':
                case 'wifi':
                    dispatch ({
                        type: CONNECTION_AVAILABLE,
                        payload: connectionInfo.type
                    });
                    break;
                default:
                    dispatch ({
                        type: CONNECTION_UNAVAILABLE,
                    });
            }

        };
    }
);
Run Code Online (Sandbox Code Playgroud)

我没有得到结果,没有 console.log,所以我认为这是错误的方式

Rob*_*gan 5

您只需在可以访问该dispatch函数的地方设置事件侦听器即可。

直接来自组件

最简单的事情(允许干净地取消订阅)是将它们设置在最顶层的连接组件中:

class MyApp extends Component {
  constructor(props) {
    super(props);

    // Dispatch an action from your event handler (and do whatever else)
    this._handleConnectionChange = (connectionInfo) => props.dispatch({ 
      type: 'CONNECTION_CHANGE', 
      connectionInfo
    });

    NetInfo.addEventListener('connectionChange', this._handleConnectionChange);
  }

  componentWillUnmount() {
    NetInfo.removeEventListener('connectionChange', this._handleConnectionChange);
  }
}

export default connect()(MyApp); // MyApp must be connected
Run Code Online (Sandbox Code Playgroud)

一点抽象 - 在 Thunk 中添加监听器

就我个人而言,我喜欢将这种事情包装在 thunk 中,以避免监听器处理混乱我的组件。这里重要的一点是,thunk 与连接的组件一样,可以访问dispatch,因此通过在 thunk 的内部定义侦听器,我们可以调度操作(或更多 thunk)以响应更改。

// connectionActions.js

let handleConnectionChange;

export function registerListeners() {
  return (dispatch) => {
    handleConnectionChange = (connectionInfo) => {
      dispatch(connectionChanged(connectionInfo));
    }
    NetInfo.addEventListener('connectionChange', handleConnectionChange);
  }
}

export function unregisterListeners() {
  return (dispatch) => {
    handleConnectionChange && NetInfo.removeEventListener('connectionChange', handleConnectionChange);
  }
}

function connectionChanged(connectionInfo) {
  return (dispatch) => {
    switch (connectionInfo.type) {
      case 'cellular':
        dispatch({
          type: CONNECTION_AVAILABLE,
          payload: connectionInfo.type
        });
        break;
      // ...Other cases
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以调度registerListeners()unregisterListeners()MyApp那里定义侦听器的详细信息:

// app.js
// ...other imports
import * as connectionActions from './connectionActions'

class MyApp extends Component {
  constructor(props) {
    super(props);
    // Dispatch your thunk to take care of the registration
    props.dispatch(connectionActions.registerListeners());
  }

  componentWillUnmount() {
    this.props.dispatch(connectionActions.unregisterListeners());
  }
}

export default connect()(MyApp)
Run Code Online (Sandbox Code Playgroud)

更抽象一点——用于监听的高阶组件

在我有多个可能的顶级组件的应用程序中(例如具有不同主页的不同构建变体,或者不属于主导航器的登录屏幕),我喜欢采用这种样板并将其包装在更高阶的组件中:

// hoc/withNetListeners.js

export default function withNetListeners(SourceComponent): {
  class HOC extends React.Component {
    constructor(props) {
      super(props);
      props.dispatch(connectionActions.registerListeners());
    }

    componentWillUnmount() {
      this.props.dispatch(connectionActions.unregisterListeners());
    }

    render() {
      return <SourceComponent {...this.props} />;
    }
  }
  return hoistStatics(HOC, SourceComponent); // Package hoist-non-react-statics
}
Run Code Online (Sandbox Code Playgroud)

然后在作为根的组件中:

// app.js
class MyApp extends Component {
  // ... Just your UI, no listeners ...
}

// Inject the listeners with a HOC. Make you `connect` last, because 
// `withNetListeners` needs to be given access to `dispatch`.
export default connect()(withNetListeners(MyApp))
Run Code Online (Sandbox Code Playgroud)