相信很多人都看过星球大战吧,那如何把你想要的信息从星球搬到自己的网站里呢?
没关系,博主我就用react 来显示如何获取信息。
如果没有了解过react, 没关系,可以点击react 学习 来获取一些基本的知识点


现在,就开始react代码之旅吧~
先找到获取star wars API 的路劲,获取星球大战的api 地址:SWAPI.

先展示结果吧:(结果的演示是随着网页的伸缩展示的结果)


代码环节:
由于安装了react之后, App.css 文件就已经有了,就不需要在里面更改内容了。只需要更改一下index.css 文件

// App.js 文件
import React, {Component} from 'react';
import './App.css';
import './index.css';function Starship(props) {let element = props.data.map((item, index) => {return (<div className="starship" key={index}><h2>{item.name}</h2><p>Model: {item.model} </p><p>Crew: {item.crew} </p><p>Length: {item.length} </p></div>);});return <div className="container">{element}</div>
}class App extends Component {constructor(props) {super(props);this.state = {starships: [],isLoaded: false,};}// 这里讲解一下这个函数是有什么用途的// componentDidMount() method is the perfect place, where we can call the setState() // method to change the state of our application and render() the updated data loaded JSX.// 在下面,可以看到setState() 的用法// 其实一句话:使用了compoenntDidMount() 方法就能获取到一些数据,比如数据来自API的。componentDidMount() {const url = 'https://swapi.dev/api/starships';fetch(url).then((response) => response.json()).then((data) => {this.setState({starships: data.results,isLoaded: true,});}).catch((error) => console.log(error));}render() {const { starships, isLoaded} = this.state;return (<React.Fragment><h1>SWAPI Starships</h1>{!isLoaded && <p>Data Loading...</p>}<Starship data={starships}/></React.Fragment>);}
}export default App;

在index.css 文件里,使用了css 中的 flex。

// index.css 文件
body {margin: 0;font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen','Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;
}code {font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',monospace;
}.container {display: flex;flex-wrap: wrap;
}.startship {display: flex;flex-direction: column;  width: 20%;margin: 5px;padding: 0 10px;border: 1px solid navy;color: blue;
}

第二种写法:

// App.js 文件
import React, { Component } from 'react';
import './App.css';
import './index.css';
import Starship from './Starship'class App extends Component {constructor(props) {super(props);this.state = {starships: [],isLoaded: false,};}// 这里讲解一下这个函数是有什么用途的// componentDidMount() method is the perfect place, where we can call the setState() // method to change the state of our application and render() the updated data loaded JSX.// 在下面,可以看到setState() 的用法// 其实一句话:使用了compoenntDidMount() 方法就能获取到一些数据,比如数据来自API的。componentDidMount() {const url = 'https://swapi.dev/api/starships';fetch(url).then((response) => response.json()).then((data) => {this.setState({starships: data.results,isLoaded: true,});}).catch((error) => console.log(error));}render() {const { starships, isLoaded} = this.state;return (<React.Fragment><h1>SWAPI Starships</h1>{!isLoaded && <p>Data Loading...</p>}<Starship data={starships}/></React.Fragment>);}
}export default App;
// Starship.js 文件
import React from 'react'
import './index.css'function Starship(props) {let element = props.data.map((item, index) => {return (<div className="startship" key={index}><h2>{item.name}</h2><p>Model: {item.model}</p><p>Crew: {item.crew}</p><p>Length: {item.length}</p></div>);});return <div className="container">{element}</div>;
}export default Starship;
// StarshipFleet.js 文件// 讲解一下,useState 和 useEffect 用途分别是什么
// useState:
// useState is a Hook that lets you add React state to function components.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// useEffect:
// The Effect Hook lets you perform side effects in function components
// 可以将useEffect 理解成在 class component 里的 componentDidMount, componentDidUpdate, 和
// componentWillUnmount 的结合体
import React, { useState, useEffect } from 'react'
import './index.css'
import Starship from './Starship'function StarshipFleet(props) {let [starships, setStarships] = useState([]);let [isLoading, setIsLoading] = useState(false);let [page, setPage] = useState(1);useEffect(() => {const url = `https://swapi.dev/api/starships/?page=${page}`;setIsLoading(true)fetch(url).then((response) => response.json()).then((data) => {setStarships(data.results);setIsLoading(false);}).catch((error) => console.log(error));}, [page]);return (<section><h1>Starships</h1>{isLoading && <p>Loading...</p>}<Starship data={starships} /></section>);
}export default StarshipFleet;
// index.js 文件
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import StarshipFleet from './StarshipFleet'ReactDOM.render(<React.StrictMode><StarshipFleet /></React.StrictMode>,document.getElementById('root')
);// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
// index.css 文件
body {margin: 0;font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen','Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;
}code {font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',monospace;
}.container {display: flex;flex-wrap: wrap;
}.startship {display: flex;flex-direction: column;  width: 20%;margin: 5px;padding: 0 10px;border: 1px solid navy;color: blue;
}

效果还是跟上面显示的一样,只是不同写法。


在这里,就在写一个有关hook 的用法,这样能稍微解决有些同学们对hook的理解。
特别注意:
只能在React function component里使用Hooks

下面是先展示一下在function component 的两种不同写法:(其实两段代码是一样的)

// function component// 第一种写法:(如果熟练,建议使用这种写法)
const Example = (props) => {// You can use Hooks here!return <div/>;// 第二种写法:
function Example(props) {// You can use Hooks here:return <div/>;
}

继续展示分别在 function component 和 class component 都需要用到 state, 改如何表示:(两种写法表达的意思是一样,只是写法不同)

// function component
import React, { useState } from 'react;function Example() {// Declare a new state variable, which we'll call "page"const [page, setPage] = useState(0);
}
// class component
import React, { Component } from 'react';class Example extends Component {constructor(props) {super(props);this.state = {page: 0};}
}

下面继续展示在function component 和 class component 使用useEffect 的区别:(不同写法,结果一样)

// function component
import React, { useState, setState } from "react";function Example() {const [page, setPage] = useState(0);useEffect(() => {document.title = `You are on the ${page}`;});return (<div><p>You are on the {page}</p><button onClick={() => setPage(page+1)}>Next Page</button></div>);
}
// class component
import React, { Component } from "react";class Example extends Component {constructor(props) {super(props);this.state = {page: 0};}// 在class component 里得加上 componentDidMount() 和 componentDidUpdate() 来代替// 在function component 里的 useEffect() componentDidMount() {document.title = `You are on the ${this.state.page}`;}componentDidUpdate() {document.title = `You are on the ${this.state.page}`;}render() {return (<div><p>You are on the {page}</p><button onClick={() => this.setState({page: this.state.page + 1})}>Next Page</button></div>    );}
}

看完之后,是不是觉得挺简单的,如果觉得不错,就用点赞或者关注或者留言来代替五星好评吧~
谢谢各位~

超容易获得星球大战信息相关推荐

  1. “安超云ArSDN”荣获“信息基础设施优秀解决方案”

    ​今天是"世界电信和信息社会日".工信部主管的权威媒体<中国电子报>公布了典型企业.创新产品与技术.优秀解决方案.安超云软件有限公司(简称安超云)推出的安超软件定义网络 ...

  2. 中国电信超 2 亿用户信息被卖,售价低至 0.01 元/条!个人信息安全何在?

    公众号关注 「运维之美」 设为「星标」,每天给你分享最新的圈内新鲜事! 1 月 3 日上午消息.日前,中国裁判文书网公布了<陈德武.陈亚华.姜福乾等侵犯公民个人信息罪二审刑事裁定书>. 经 ...

  3. 使用jQuery开发一个响应式超酷整合RSS信息阅读杂志

    在线演示1 本地下载 申请达人,去除赞助商链接 如果大家喜欢阅读博客文章的话,可能都会使用RSS阅读器,今天这里我们将使用jQuery来开发一个响应式的RSS信息阅读应用,使用它你可以将你喜欢的RSS ...

  4. 【图像超分辨率】Deep Learning for Multiple-Image Super-Resolution

    Deep Learning for Multiple-Image Super-Resolution 摘要 I. 引言 A. 相关工作 B. 贡献 II. 提议的EVONET算法 III. 实验 IV. ...

  5. 数据可视化 信息可视化_动机可视化

    数据可视化 信息可视化 John Snow's map of Cholera cases near London's Broad Street. 约翰·斯诺(John Snow)在伦敦宽街附近的霍乱病 ...

  6. 深度学习图像融合_基于深度学习的图像超分辨率最新进展与趋势【附PDF】

    因PDF资源在微信公众号关注公众号:人工智能前沿讲习回复"超分辨"获取文章PDF 1.主题简介 图像超分辨率是计算机视觉和图像处理领域一个非常重要的研究问题,在医疗图像分析.生物特 ...

  7. 1月第1周业务风控关注 | 四部门联合印发App违法违规收集使用个人信息行为认定方法

    易盾业务风控周报每周报道值得关注的安全技术和事件,包括但不限于内容安全.移动安全.业务安全和网络安全,帮助企业提高警惕,规避这些似小实大.影响业务健康发展的安全风险. 1.四部门联合印发App违法违规 ...

  8. 贝叶斯分析-学习笔记(超干的干货)

    文章目录 第一章.绪论 一.常见随机变量分布 1.二项分布: 2.Poisson分布 3.几何分布 4.帕斯卡分布(负二项分布) 5.多项分布(二项分布的推广) 6.均匀分布 7.指数分布 8.正态分 ...

  9. [Java] 超简图床(Java版) —— 专为Api而生

    v1.2已更新,添加新浪图床v1.1已更新,支持保存配置,配置不会随着服务器重启而被重置 PHP版本请看这里:https://www.52pojie.cn/forum.php?mod=viewthre ...

最新文章

  1. 计算机视觉以及它在商业中是如何应用的?
  2. Mysql 另类盲注中的一些技巧
  3. 操作canal,报错:Caused by: java.io.IOException: end of stream when reading header
  4. 理解Docker(5):Docker 网络
  5. python中os.path.isdir()等函数的作用及用法
  6. mysql如何查找某字段所在表
  7. della计算机驱动检测,nexus6安装BPTOOLS中的diag驱动图文教程
  8. linux OOM-killer机制(杀掉进程,释放内存)
  9. 在一个由 'L' , 'R' 和 'X' 三个字符组成的字符串(例如RXXLRXRXL)中进行移动操作。一次移动操作指用一个LX替换一个XL,或者用一个XR替换一个RX。现给定起始...
  10. Emgu-WPF 激光雷达研究-移动物体跟踪2
  11. 接口测试——jemter生成HTML测试报告
  12. [转载] 语言程序设计第4版黄洪艺_计算机二级教程 Python语言程序设计 第8章python计算生态...
  13. spine怎么取消版本升级_设置 - Spine用户指南
  14. mysql例题_mysql 练习题
  15. php app用户验证失败,无法验证app需要互联网连接以认证 建议更换登陆的AppleID
  16. 两种自动化测试工具AutoRunner与Selenium的对比
  17. React Native 参考资料 (转自简书)
  18. 数据分析方法-AARRR模型分析方法
  19. 微信PC端技术研究(2)-拿下语音
  20. AR红包大战,抢的不是钱而是发展机会

热门文章

  1. (四)52周存钱挑战3.0-----for循环遍历列表、range()
  2. iPad 变身做电脑显示器
  3. Photoshop照片一键转换手绘效果图动作
  4. 中科院大学计算机科学与技术王伟强,王伟强-中国科学院大学-UCAS
  5. orCAD原理图 DRC检查
  6. Python 基于tkinter模块的GUI可视化学生成绩管理系统实现(含文件保存)
  7. 华为 、锐捷、新华三、睿易网络设备怎么选
  8. MapReduce打包jar包并运行的步骤操作以及重要的注意事项
  9. 第6-8课:分离轴算法(SAT)与碰撞检测(图文篇)
  10. java.net.MalformedURLException异常说明