相信很多人都看过星球大战吧,那如何把你想要的信息从星球搬到自己的网站里呢?
没关系,博主我就用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>
);
}
}
看完之后,是不是觉得挺简单的,如果觉得不错,就用点赞或者关注或者留言来代替五星好评吧~
谢谢各位~