【问题标题】:Refetch queries in react-native with graphql使用 graphql 在 react-native 中重新获取查询
【发布时间】:2019-12-09 07:17:39
【问题描述】:

我是初学者,我尝试学习 graphql。我想创建一个应用程序,它从反应 Web 应用程序更新数据(实时)以使用 graphql 反应本机移动应用程序。当我按下 OK 按钮时,在 web 应用程序中很容易重新获取查询。在移动应用中,当我按下网络应用中的按钮时,我不知道如何重新获取查询。

我尝试通过 websockets(socket.io) 传输数据,最后我设法传递了数据,但这很耗时。

这里是WEB APP

和 这是我想做的

使用 react.js 构建的网络应用

使用 react-native.js 构建的移动应用

这是我的 react-native 代码。我不知道如何以及在哪里使用 refetch 查询。

App.js

import React, { Component } from "react";
import ApolloClient from "apollo-boost";
import { ApolloProvider } from "react-apollo";
import { View, Text } from "react-native";
import BookList from "./components/BookList";
//apollo client
const client = new ApolloClient({
  uri: "http://XXX.XXX.X.X:4000/graphql"
});

class App extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
        <View>
          <BookList />
        </View>
      </ApolloProvider>
    );
  }
}

export default App;

BookList.js

import React, { Component } from "react";
import { graphql } from "react-apollo";
import { Button, View, Text } from "react-native";
import { gql } from "apollo-boost";
import io from "socket.io-client";

const getBooksQuery = gql`
  {
    books {
      name
      id
      genre
    }
  }
`;

class BookList extends Component {

  displayBooks = () => {
    var data = this.props.data;

    if (data.loading) {
      return <Text>loading books...</Text>;
    } else {
      return data.books.map(book => {
        return <Text>{book.name}</Text>;
      });
    }
  };
  render() {
    return <View>{this.displayBooks()}</View>;
  }
}

export default graphql(getBooksQuery)(BookList);

在网络应用程序中很容易应用某事,因为我将 refetch 查询放在我按下按钮时的函数中:

submitForm = e => {
    e.preventDefault();
    this.props.addBookMutation({
      variables: {
        name: this.state.name,
        genre: this.state.genre,
        authorid: this.state.authorid
      },
      refetchQueries: [{ query: getBooksQuery }]
    });
  };

*对不起我的英语

【问题讨论】:

    标签: javascript reactjs react-native graphql express-graphql


    【解决方案1】:

    所以根据阿波罗的文件

    您可以像使用 React Web 一样将 Apollo 与 React Native 一起使用。

    这里是关于使用 react-native 实现的相应页面。

    https://www.apollographql.com/docs/react/recipes/react-native/

    要通过 graphQL 中的套接字获取数据,您需要使用 subscriptions

    请按照以下步骤操作;

    1. 在您的后端项目中创建订阅模式和订阅函数,以便在图书更新时分派。我不知道您将哪个服务器库用于后端,但我强烈建议您使用 apollo-server here
    2. 在您的移动应用程序中,您需要在 getBooksQuery 中 subscribeToMore 获取所有书籍。

    当图书更新时,您的服务器会将更新后的图书发送给订阅的客户端,并且您可以从订阅后的移动应用程序中获取它。

    PS:您可以使用howtographql 来学习更新版本的 apollo。 (提供渲染道具功能的组件)

    【讨论】:

      猜你喜欢
      • 2018-01-01
      • 2020-09-22
      • 2021-03-01
      • 2020-01-20
      • 2016-12-25
      • 2019-12-20
      • 1970-01-01
      • 2018-02-01
      • 2019-11-28
      相关资源
      最近更新 更多