- GraphQL Tutorial
- GraphQL - Home
- GraphQL - Introduction
- GraphQL - Environment Setup
- GraphQL - Architecture
- GraphQL - Application Components
- GraphQL - Example
- GraphQL - Type System
- GraphQL - Schema
- GraphQL - Resolver
- GraphQL - Query
- GraphQL - Mutation
- GraphQL - Validation
- GraphQL - JQuery Integration
- GraphQL - React Integration
- GraphQL - Apollo Client
- GraphQL - Authenticating Client
- GraphQL - Caching
- GraphQL Useful Resources
- GraphQL - Quick Guide
- GraphQL - Useful Resources
- GraphQL - Discussion
GraphQL - React 集成
React 是一个用于构建用户界面的 Javascript 库。本章解释了如何将 GraphQL 与 React 应用程序集成。
插图
设置 React 项目的最快方法是使用 Create React App 工具。在后续部分中,我们将学习如何设置服务器和客户端。
设置服务器
要设置服务器,请按照以下步骤操作 -
第 1 步 - 下载并安装项目所需的依赖项
创建一个文件夹react-server-app。 从终端将目录更改为 react-server-app 。请按照“环境设置”一章中说明的步骤 3 至 5 进行操作。
第 2 步 - 创建架构
在项目文件夹 react-server-app中添加schema.graphql文件 并添加以下代码 -
type Query
{
greeting: String
sayHello(name:String!):String
}
该文件定义了两个查询——greeting 和 sayHello。sayHello 查询接受一个字符串参数并返回另一个字符串。sayHello() 函数的参数不为空。
第 3 步 - 创建解析器
在项目文件夹中创建文件resolvers.js并添加以下代码 -
const Query =
{
greeting: () => 'Hello GraphQL From TutorialsPoint !!' ,
sayHello:(root,args,context,info) => `Hi ${args.name} GraphQL server says Hello to you!!`
}
module.exports = {Query}
这里的greeting和sayHello是两个解析器。在 sayHello 解析器中,可以通过 args 访问传递给 name 参数的值。要访问模块外部的解析器函数,必须使用 module.exports 导出 Query 对象。
第 4 步 - 运行应用程序
创建一个 server.js 文件。请参阅环境设置一章中的步骤 8。在终端中执行命令npm start 。服务器将在 9000 端口上启动并运行。在这里,我们使用 GraphiQL 作为客户端来测试应用程序。
打开浏览器并输入 URL http://localhost:9000/graphiql。在编辑器中输入以下查询 -
{
greeting,
sayHello(name:"Mohtashim")
}
来自服务器的响应如下 -
{
"data": {
"greeting": "Hello GraphQL From TutorialsPoint !!",
"sayHello": "Hi Mohtashim GraphQL server says Hello to you!!"
}
}
设置客户端
为客户端打开一个新终端。在执行客户端应用程序之前,服务器终端应保持运行。React 应用程序将在端口号 3000 上运行,服务器应用程序将在端口号 9000 上运行。
步骤 1 - 创建一个 React 项目 hello-world-client
在客户端中,输入以下命令 -
npx create-react-app hello-world-client
这将安装典型反应应用程序所需的一切。npx实用程序和create-react-app工具创建一个名为 hello-world-client 的项目。安装完成后,在VSCode中打开项目。
步骤 2 - 启动 hello-world-client
将终端中的当前文件夹路径更改为 hello-world-client。输入 npm start 启动项目。这将在端口 3000 运行开发服务器,并自动打开浏览器并加载索引页面。
这显示在下面的屏幕截图中 -
步骤 3 - 修改应用程序组件
在 src 文件夹内的 App.js 中,添加两个函数,一个用于加载问候语,另一个用于加载 sayHello 消息。
以下是 loadGreeting 函数,它发送 GraphQL 查询以获取问候语。
async function loadGreeting() {
const response = await fetch('http://localhost:9000/graphql', {
method:'POST',
headers:{'content-type':'application/json'},
body:JSON.stringify({query:'{greeting}'})
})
const rsponseBody = await response.json();
return rsponseBody.data.greeting;
console.log("end of function")
}
以下是loadSayhello函数,它发送 GraphQL 查询 sayHello -
async function loadSayhello(name) {
const response = await fetch('http://localhost:9000/graphql', {
method:'POST',
headers:{'content-type':'application/json'},
body:JSON.stringify({query:`{sayHello(name:"${name}")}`})
})
}
完整的App.js文件如下所示 -
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
async function loadGreeting() {
const response = await fetch('http://localhost:9000/graphql', {
method:'POST',
headers:{'content-type':'application/json'},
body:JSON.stringify({query:'{greeting}'})
})
const rsponseBody = await response.json();
return rsponseBody.data.greeting;
console.log("end of function")
}
async function loadSayhello(name) {
const response = await fetch('http://localhost:9000/graphql', {
method:'POST',
headers:{'content-type':'application/json'},
body:JSON.stringify({query:`{sayHello(name:"${name}")}`})
})
const rsponseBody = await response.json();
return rsponseBody.data.sayHello;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {greetingMessage:'',sayHelloMessage:'',userName:''}
this.updateName = this.updateName.bind(this);
this.showSayHelloMessage = this.showSayHelloMessage.bind(this);
this.showGreeting = this.showGreeting.bind(this);
}
showGreeting() {
loadGreeting().then(g => this.setState({greetingMessage:g+" :-)"}))
}
showSayHelloMessage() {
const name = this.state.userName;
console.log(name)
loadSayhello(name).then(m => this.setState({sayHelloMessage:m}))
}
updateName(event) {
this.setState({userName:event.target.value})
}
render() {
return (
<div className = "App">
<header className = "App-header">
<img src = {logo} className = "App-logo" alt = "logo" />
<h1 className = "App-title">Welcome to React</h1>
</header>
<br/><br/>
<section>
<button id = "btnGreet" onClick = {this.showGreeting}>Greet</button>
<br/> <br/>
<div id = "greetingDiv">
<h1>{this.state.greetingMessage}</h1>
</div>
</section>
<hr/>
<section>
Enter a name:<input id = "txtName" type = "text" onChange = {this.updateName}
value = {this.state.userName}/>
<button id = "btnSayhello" onClick = {this.showSayHelloMessage}>SayHello</button>
<br/>
user name is:{this.state.userName} <br/>
<div id = "SayhelloDiv">
<h1>{this.state.sayHelloMessage}</h1>
</div>
</section>
</div>
);
}
}
export default App;
两个应用程序运行后,单击欢迎按钮。接下来,在文本框中输入名称并单击 sayHello 按钮。输出如下 -
