我使用RTK查询.

如果我关闭我的互联网连接并导航到一个屏幕,我看不到Loader,或者其他什么我什么也看不到.所以,当我打开我的互联网连接时,什么也没有发生.当互联网离线时,我如何告诉用户我给他发送了一条消息,而当互联网处于在线状态时,RTK查询自动检索数据?

TSX车

const ShoppingCart: React.FC<Props> = ({}) => {
  const user_id = useSelector((state: RootState) => state.Auth.user.user_id);

  const { data, isFetching, isLoading } = useCartQuery({user_id});

  if(isLoading) {
    return (
      <Loader />
    )
  } else if(data && data.length > 0) {
    return (
      <ShoppingCartComponent
        products={data}
      />
    )
  } else if(data && data.length === 0) {
    return (
      <ShoppingCartEmpty />
    )
  }
}

export default ShoppingCart;

Cart.ts API Cart.ts

  reducerPath: 'ShoppingCartApi',
  baseQuery: fetchBaseQuery({ baseUrl: `${API_ENDPOINT}/` }),
  tagTypes: ['CART'],
  endpoints: (builder) => ({
    cart: builder.query<IProduct[], { user_id?: number; unlogged_uuid?: string; }>({
      query: (data) => ({
        url: '/cart',
        method: 'POST',
        body: data
      }),
      providesTags: ['CART']
    }),

推荐答案

您可以使用navigator.onLine来判断用户的设备当前是否在线.然后监听在线事件,该事件在设备的互联网连接恢复时触发,并重新获取数据.

const ShoppingCart: React.FC<Props> = ({}) => {
  const user_id = useSelector((state: RootState) => state.Auth.user.user_id);
  const { data, isFetching, isLoading, refetch } = useCartQuery({user_id});

  useEffect(() => {
    const handleOnlineEvent = () => {
      // Refetch data from the API when the online event is fired
      refetch();
    };

    window.addEventListener('online', handleOnlineEvent);

    return () => {
      window.removeEventListener('online', handleOnlineEvent);
    };
  }, []);

  if (!navigator.onLine) {
    return (
      <div>
        <p>You are currently offline. Please check your internet connection and try again.</p>
      </div>
    );
  }

  if (isLoading) {
    return (
      <Loader />
    )
  } else if(data && data.length > 0) {
    return (
      <ShoppingCartComponent
        products={data}
      />
    )
  } else if(data && data.length === 0) {
    return (
      <ShoppingCartEmpty />
    )
  }
}

React-native相关问答推荐

添加REACT-Native-SVG时出现错误-失败:构建失败并出现异常

如何在使用嵌套的堆栈导航器在选项卡之间导航后弹出到堆栈顶部?

在第二次加载时仅将本机应用程序设置为状态

每当我在 React Native Tab Navigator 中切换标签时触发 UseEffect

如何在 React Native 中测量我的应用程序的数据使用情况?

为应用创建单个 MobX store 的最佳方式是什么?

react native 中 componentDidMount 和 componentDidUpdate 有什么区别

如何在 mac 上卸载 react-native-cli?

错误:安装 react-native-elements 后无法识别字体系列 Material Design 图标?

从组件的 style属性中获取 CSS 属性值

加载远程图像失败后加载本map像

React Native 得到这个错误'Unrecognized operator abs'

如何在自定义组件上使用 onPress?

react-native 元素/目录 struct 设置

我们可以在 react webapp 和 react native 应用程序之间共享代码吗,并且可以在 react-native 生产环境中使用

Expo LAN 配置不适用于新的 ReactNative 元素

当前未启用语法nullishCoalescingOperator

zIndex 不适用于react-native元素

使用expo react-native链接?

使用 TouchableWithoutFeedback react-native onPress 不起作用