当前位置: 首页 > news >正文

React 全栈体系(八)

第四章 React ajax

三、案例 – github 用户搜索

2. 代码实现

2.3 axios 发送请求

Search
/* src/components/Search/index.jsx */
import React, { Component } from "react";
import axios from 'axios'export default class Search extends Component {search = () => {//获取用户的输入(连续解构赋值+重命名)const { keyWordElement:{value:keyword} } = thisconsole.log(keyword);//发送网络请求axios.get(`https://api.github.com/search/users?q=${keyword}`).then(response => {console.log('c', response.data);},error => {console.log('d', error);})}render() {return (<section className="jumbotron"><h3 className="jumbotron-heading">Search Github Users</h3><div><input ref={c => this.keyWordElement = c} type="text" placeholder="enter the name you search" />&nbsp;<button onClick={this.search}>Search</button></div></section>);}
}

2.4 展示数据

2.4.1 App
/* src/App.jsx */
import React, { Component } from "react";
import Search from "./components/Search";
import List from "./components/List";export default class App extends Component {state = {users:[]} //初始化状态,users初始值为数组saveUsers = (users)=>{this.setState({users})}render() {const {users} = this.statereturn (<div className="container"><Search saveUsers={this.saveUsers}/><List users={users}/></div>);}
}
2.4.2 Search
/* src/components/Search/index.jsx */
import React, { Component } from "react";
import axios from 'axios'export default class Search extends Component {search = () => {//获取用户的输入(连续解构赋值+重命名)const { keyWordElement:{value:keyword} } = this//发送网络请求axios.get(`https://api.github.com/search/users?q=${keyword}`).then(response => {this.props.saveUsers(response.data.items)},error => {console.log('d', error);})}render() {return (<section className="jumbotron"><h3 className="jumbotron-heading">Search Github Users</h3><div><input ref={c => this.keyWordElement = c} type="text" placeholder="enter the name you search" />&nbsp;<button onClick={this.search}>Search</button></div></section>);}
}
2.4.3 List
/* src/components/List/index.jsx */
import React, { Component } from "react";
import "./index.css";export default class List extends Component {render() {return (<div className="row">{this.props.users.map((userObj) => {return (<div key={userObj.id} className="card"><a rel="noreferrer" href={userObj.html_url} target="_blank"><imgalt="head_portrait"src={userObj.avatar_url}style={{ width: "100px" }}/></a><p className="card-text">{userObj.login}</p></div>);})}</div>);}
}

2.5 完成案例

2.5.1 App
/* src/App.jsx */
import React, { Component } from "react";
import Search from "./components/Search";
import List from "./components/List";export default class App extends Component {state = {//初始化状态users: [], //users初始值为数组isFirst: true, //是否为第一次打开页面isLoading: false, //标识是否处于加载中err: "", //存储请求相关的错误信息};//更新App的stateupdateAppState = (stateObj) => {this.setState(stateObj);};render() {const { users } = this.state;return (<div className="container"><Search updateAppState={this.updateAppState} /><List {...this.state} /></div>);}
}
2.5.2 Search
/* src/components/Search/index.jsx */
import React, { Component } from "react";
import axios from "axios";export default class Search extends Component {search = () => {//获取用户的输入(连续解构赋值+重命名)const {keyWordElement: { value: keyword },} = this;//发送请求前通知App更新状态this.props.updateAppState({ isFirst: false, isLoading: true });//发送网络请求axios.get(`https://api.github.com/search/users?q=${keyword}`).then((response) => {//请求成功后通知App更新状态this.props.updateAppState({isLoading: false,users: response.data.items,});},(error) => {//请求失败后通知App更新状态this.props.updateAppState({ isLoading: false, err: error.message });});};render() {return (<section className="jumbotron"><h3 className="jumbotron-heading">Search Github Users</h3><div><inputref={(c) => (this.keyWordElement = c)}type="text"placeholder="enter the name you search"/>&nbsp;<button onClick={this.search}>Search</button></div></section>);}
}
2.5.3 List
/* src/components/List/index.jsx */
import React, { Component } from "react";
import "./index.css";export default class List extends Component {render() {const { users, isFirst, isLoading, err } = this.props;return (<div className="row">{isFirst ? (<h2>Welcome, enter a keyword and then click search!</h2>) : isLoading ? (<h2>Loading......</h2>) : err ? (<h2 style={{ color: "red" }}>{err}</h2>) : (users.map((userObj) => {return (<div key={userObj.id} className="card"><a rel="noreferrer" href={userObj.html_url} target="_blank"><imgalt="head_portrait"src={userObj.avatar_url}style={{ width: "100px" }}/></a><p className="card-text">{userObj.login}</p></div>);}))}</div>);}
}

四、消息订阅-发布机制

1. 工具库

  • PubSubJS

2. 下载

  • npm install pubsub-js --save

3. 使用

  • import PubSub from ‘pubsub-js’ //引入
  • PubSub.subscribe(‘delete’, function(data){ }); //订阅
  • PubSub.publish(‘delete’, data) //发布消息

4. github 用户搜索代码重构

4.1 App

/* src/App.jsx */
import React, { Component } from "react";
import Search from "./components/Search";
import List from "./components/List";export default class App extends Component {render() {return (<div className="container"><Search /><List /></div>);}
}

4.2 Search

/* src/components/Search/index.jsx */
import React, { Component } from "react";
import PubSub from "pubsub-js";
import axios from "axios";export default class Search extends Component {search = () => {//获取用户的输入(连续解构赋值+重命名)const {keyWordElement: { value: keyword },} = this;//发送请求前通知List更新状态PubSub.publish("alex", { isFirst: false, isLoading: true });//发送网络请求axios.get(`https://api.github.com/search/users?q=${keyword}`).then((response) => {//请求成功后通知List更新状态PubSub.publish("alex", {isLoading: false,users: response.data.items,});},(error) => {//请求失败后通知List更新状态PubSub.publish("alex", { isLoading: false, err: error.message });});};render() {return (<section className="jumbotron"><h3 className="jumbotron-heading">Search Github Users</h3><div><inputref={(c) => (this.keyWordElement = c)}type="text"placeholder="enter the name you search"/>&nbsp;<button onClick={this.search}>Search</button></div></section>);}
}

4.3 List

/* src/components/List/index.jsx */
import React, { Component } from "react";
import PubSub from "pubsub-js";
import "./index.css";export default class List extends Component {state = {//初始化状态users: [], //users初始值为数组isFirst: true, //是否为第一次打开页面isLoading: false, //标识是否处于加载中err: "", //存储请求相关的错误信息};componentDidMount() {this.token = PubSub.subscribe("alex", (_, stateObj) => {this.setState(stateObj);});}componentWillUnmount() {PubSub.unsubscribe(this.token);}render() {const { users, isFirst, isLoading, err } = this.state;return (<div className="row">{isFirst ? (<h2>Welcome, enter a keyword and then click search!</h2>) : isLoading ? (<h2>Loading......</h2>) : err ? (<h2 style={{ color: "red" }}>{err}</h2>) : (users.map((userObj) => {return (<div key={userObj.id} className="card"><a rel="noreferrer" href={userObj.html_url} target="_blank"><imgalt="head_portrait"src={userObj.avatar_url}style={{ width: "100px" }}/></a><p className="card-text">{userObj.login}</p></div>);}))}</div>);}
}

五、扩展:Fetch

1. 文档

  • https://github.github.io/fetch/

2. 特点

  • fetch: 原生函数,不再使用 XmlHttpRequest 对象提交 ajax 请求
  • 老版本浏览器可能不支持

3. 相关 API

3.1 GET 请求

fetch(url).then(function(response) {return response.json()}).then(function(data) {console.log(data)}).catch(function(e) {console.log(e)});

3.2 POST 请求

fetch(url, {method: "POST",body: JSON.stringify(data),
}).then(function(data) {console.log(data)
}).catch(function(e) {console.log(e)
})

4. github 用户搜索代码 - fetch

Search

/* src/components/Search/index.jsx */
import React, { Component } from "react";
import PubSub from "pubsub-js";export default class Search extends Component {search = async()=>{//获取用户的输入(连续解构赋值+重命名)const {keyWordElement:{value:keyWord}} = this//发送请求前通知List更新状态PubSub.publish('alex',{isFirst:false,isLoading:true})//#region 发送网络请求---使用axios发送/* axios.get(`https://api.github.com/search/users?q=${keyWord}`).then(response => {//请求成功后通知List更新状态PubSub.publish('alex',{isLoading:false,users:response.data.items})},error => {//请求失败后通知App更新状态PubSub.publish('alex',{isLoading:false,err:error.message})}) *///#endregion//发送网络请求---使用fetch发送(未优化)/* fetch(`https://api.github.com/search/users?q=${keyWord}`).then(response => {console.log('联系服务器成功了');return response.json()},error => {console.log('联系服务器失败了',error);return new Promise(()=>{})}).then(response => {console.log('获取数据成功了',response);},error => {console.log('获取数据失败了',error);}) *///发送网络请求---使用fetch发送(优化)try {const response= await fetch(`https://api.github.com/search/users?q=${keyWord}`)const data = await response.json()PubSub.publish('alex',{isLoading:false,users:data.items})} catch (error) {PubSub.publish('alex',{isLoading:false,err:error.message})}}render() {return (<section className="jumbotron"><h3 className="jumbotron-heading">Search Github Users</h3><div><inputref={(c) => (this.keyWordElement = c)}type="text"placeholder="enter the name you search"/>&nbsp;<button onClick={this.search}>Search</button></div></section>);}
}

六、总结

1.设计状态时要考虑全面,例如带有网络请求的组件,要考虑请求失败怎么办。
2.ES6小知识点:解构赋值+重命名let obj = {a:{b:1}}const {a} = obj; //传统解构赋值const {a:{b}} = obj; //连续解构赋值const {a:{b:value}} = obj; //连续解构赋值+重命名
3.消息订阅与发布机制1.先订阅,再发布(理解:有一种隔空对话的感觉)2.适用于任意组件间通信3.要在组件的componentWillUnmount中取消订阅
4.fetch发送请求(关注分离的设计思想)try {const response= await fetch(`/api1/search/users2?q=${keyWord}`)const data = await response.json()console.log(data);} catch (error) {console.log('请求出错',error);}
http://www.lryc.cn/news/170673.html

相关文章:

  • 4.开放-封闭原则
  • oracle递归with子句
  • 如何在Proteus进行STM32F103C8T6模拟以及keil5开发
  • C# OpenCvSharp 图片模糊检测(拉普拉斯算子)
  • 志高团队:广阔前景 全新的投资理财体验
  • 基于自编译的onlyoffice镜像,关于修改字体的问题
  • 1.wifi开发,wifi连接初次连接电脑没有识别,搭建环境
  • 【JAVA-Day25】解密进制转换:十进制向R进制和R进制向十进制的过程
  • 牛客网字节面试算法刷题记录
  • QT连接Sqlite
  • ChatGPT AIGC 完成各省份销售动态可视化分析
  • 基于SpringBoot+Vue的餐饮管理系统设计与实现
  • 2023 亲测好用版VScode配置文件
  • jmeter基础压力教程
  • 图片格式大全
  • 5.14.1.2 Get Log Page – Smart Log
  • 【深度学习实验】线性模型(一):使用NumPy实现简单线性模型:搭建、构造损失函数、计算损失值
  • springcloud3 分布式事务-seata的四种模式总结以及异地容灾
  • 【办公类-16-06】20230901大班运动场地分配表-斜线排列、5天循环、不跳节日,手动修改节日”(python 排班表系列)
  • java学习--day13 (static关键字、异常)
  • 英飞凌TC3xx--深度手撕HSM安全启动(五)--TC3xx HSM启动流程、通信机制分析
  • 【窗体】Winform两个窗体之间通过委托事件进行值传递,基础篇
  • mac使用指南
  • Git 版本控制系统 笔记
  • VRTK4⭐四.和 UI 元素交互
  • 【STM32】SDIO—SD 卡读写01
  • SpringCloud Alibaba 整合Sentinel的基本使用
  • Linux中如何执行命令
  • 基于51单片机的智能病房呼叫系统的设计与实现
  • js在一个时间范围内产生一个随机时间