gpt4 book ai didi

javascript - 在带有 Redux 的 React Native 中使用 NetInfo 中间件

转载 作者:搜寻专家 更新时间:2023-10-31 23:37:07 25 4
gpt4 key购买 nike

我想在所有组件中测试用户是否已连接到互联网。

我可以在每个组件中使用 NetInfo,但由于我使用的是 redux,我认为使用中间件(?)可以更轻松地完成。

我用过

import { createStore, applyMiddleware } from 'redux';   

const netInfo = store => next => action => {
const listener = (isConnected) => {
store.dispatch({
type: types.NET_INFO_CHANGED,
isConnected,
});
};

NetInfo.isConnected.addEventListener('change', listener);
NetInfo.isConnected.fetch().then(listener);

return next(action);
};

const store = createStore(AppReducer, applyMiddleware(netInfo));

AppReducer 就是 combineReducers(navReducer, netInfoReducer, ...)

它似乎确实有效,但我真的很担心它的表现是否足够好。它似乎只运行一次,但我从不删除监听器或任何东西。

如果您想用 isConnected 变量填充所有组件,您通常会这样做吗?

最佳答案

我会创建一个 Higher-Order Component为此:

import React, { Component } from 'react';
import { NetInfo } from 'react-native';

function withNetInfo(WrappedComponent) {
return class extends Component {
constructor(props) {
super(props);
this.state = {};
this.handleChange = this.handleChange.bind(this);
NetInfo.isConnected.fetch().then(this.handleChange);
}

componentDidMount() {
NetInfo.isConnected.addEventListener('change', this.handleChange);
}

componentWillUnmount() {
NetInfo.isConnected. removeEventListener('change', this.handleChange);
}

handleChange(isConnected) {
this.setState({ isConnected });
}

render() {
return <WrappedComponent isConnected={this.state.isConnected} {...this.props} />;
}
}
}

export default withNetInfo;

然后你可以包装任何你想渲染的组件:

class MyComponent extends Component {
render() {
const { isConnected } = this.props;

return(
<View>
<Text>
{`Am I connected? ${isConnected}`}
</Text>
</View>
);
}
}

export default withNetInfo(MyComponent);

好处:如果你想保留原始组件的静态方法(如果你已经定义了一些),你应该使用包 hoist-non-react-statics复制非 react 特定静态:

import React, { Component } from 'react';
import { NetInfo } from 'react-native';
import hoistStatics from 'hoist-non-react-statics';

function withNetInfo(WrappedComponent) {
class ExtendedComponent extends Component {
constructor(props) {
super(props);
this.state = {};
this.handleChange = this.handleChange.bind(this);
NetInfo.isConnected.fetch().then(this.handleChange)
}

componentDidMount() {
NetInfo.isConnected.addEventListener('change', this.handleChange);
}

componentWillUnmount() {
NetInfo.isConnected. removeEventListener('change', this.handleChange);
}

handleChange(isConnected) {
this.setState({ isConnected });
}

render() {
return <WrappedComponent isConnected={this.state.isConnected} {...this.props} />;
}
}
return hoistStatics(ExtendedComponent, WrappedComponent);
}

export default withNetInfo;

关于javascript - 在带有 Redux 的 React Native 中使用 NetInfo 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44245890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com