我是初学者,我尝试学习 graphql。我想创建一个应用程序来更新来自 react 网络应用程序的数据(实时)以使用 graphql react native 移动应用程序。当我按下 OK 按钮时,在 Web 应用程序中很容易重新获取查询。在移动应用程序中,当我从网络应用程序中按下按钮时,我不知道如何重新获取查询。
我尝试通过 websockets(socket.io) 传输数据,最后我设法传递了数据,但这很耗时。
这里是WEB APP
和 这是我想做的
使用 react.js 构建的网络应用
使用 react-native.js 构建的移动应用
这是我的 native react 代码。我不知道如何以及在何处使用重新获取查询。
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);
在 web 应用程序中很容易应用某事,因为我将重新获取查询放在函数中,当我按下这样的按钮时:
submitForm = e => {
e.preventDefault();
this.props.addBookMutation({
variables: {
name: this.state.name,
genre: this.state.genre,
authorid: this.state.authorid
},
refetchQueries: [{ query: getBooksQuery }]
});
};
*对不起我的英语
最佳答案
所以根据Apollo的文档
You can use Apollo with React Native exactly as you would with React Web.
这里是关于使用 react-native 实现的相应页面。
https://www.apollographql.com/docs/react/recipes/react-native/
要在 graphQL 中通过套接字获取数据,您需要使用订阅。
请按照以下步骤操作;
- 在您的后端项目中创建一个订阅架构和订阅函数,以便在图书更新时进行调度。我不知道您使用哪个服务器库作为后端,但我强烈建议您使用 apollo-server here .
- 在您的移动应用中,您需要 subscribeToMore在 getBooksQuery 中,您可以获得所有书籍。
当一本书更新时,您的服务器会将更新后的书发送给订阅的客户端,并且您可以在订阅后从移动应用程序中获取它。
PS:你可以使用howtographql学习更新版本的 Apollo 。 (提供渲染 Prop 功能的组件)
关于javascript - 使用 graphql 在 react-native 中重新获取查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57296363/