React是一个用于构建用户界面的Javascript库。本章说明如何将GraphQL与React应用程序集成。
设置React项目的最快方法是使用 Create React App 工具。在接下来的部分中,无涯教程将学习如何设置服务器和客户端。
要设置服务器,请遵循以下步骤-
创建一个文件夹 react-server-app 。从终端将目录更改为 react-server-app 。请按照"环境设置"一章中介绍的步骤3至5进行操作。
在项目文件夹 react-server-app 中添加 schema.graphql 文件并添加以下代码-
type Query { greeting: String sayHello(name:String!):String }
该文件定义了两个查询-greeting和sayHello。 ``sayHello''查询接受一个字符串参数并返回另一个字符串。 sayHello()函数的参数不为null。
在项目文件夹中创建文件 resolvers.js 并添加以下代码-
const Query = { greeting: () => 'Hello GraphQL From LearnFk !!' , sayHello:(root,args,context,info) => `Hi ${args.name} GraphQL server says Hello to you!!` } module.exports={Query}
问候和sayHello是两个解析器。在sayHello解析器中,可以通过args访问传递给name参数的值。要访问模块外部的解析器函数,必须使用module.exports导出查询对象 。
创建一个server.js文件。请参阅环境设置一章中的步骤8。在终端中执行命令 npm start 。服务器将启动并在9000端口上运行。在这里使用GraphiQL作为客户端来测试应用程序。
打开浏览器并输入URL http://localhost:9000/graphiql 。在编辑器中键入以下查询-
{ greeting, sayHello(name:"Learnfk") }
来自服务器的响应如下-
{ "data": { "greeting": "Hello GraphQL From LearnFk !!", "sayHello": "Hi Learnfk GraphQL server says Hello to you!!" } }
为客户端打开一个新终端。在执行客户端应用程序之前,服务器终端应保持运行。 React应用程序将在端口号3000上运行,服务器应用程序在端口号9000上运行。
在客户端中,键入以下命令-
npx create-react-app hello-world-client
这将安装典型的React应用程序所需的一切。 npx 实用程序和 create-react-app 工具创建一个名称为hello-world-client的项目。安装完成后,在VSCode中打开项目。
将终端中的当前文件夹路径更改为hello-world-client。输入npm start启动项目。这将在端口3000上运行开发服务器并自动打开浏览器并加载索引页面。
这显示在下面给出的屏幕截图中-
在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 函数,该函数为sayHello发送GraphQL查询-
链接:https://www.learnfk.comhttps://www.learnfk.com/graphql/graphql-react-integration.html
来源:LearnFk无涯教程网
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按钮。输出将如下所示-
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)