2023年5月1日
react基本原理
#
https://www.bilibili.com/video/BV1be411w7iF/?spm_id_from=333.999.0.0&vd_source=dfa9bf517c1718c832302c15f80df948
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="short icon" href="#">
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<title>Document</title>
</head>
<body>
<div id="root">
</div>
<script type="text/babel">
const root = ReactDOM.createRoot(document.getElementById("root"));
// root.render(<h1>宝可梦</h1>);
// const pokemons = ["皮卡丘", "杰尼龟", "小火龙"];
// 类/函数的方式写组件
class App extends React.Component {
// 构造函数->渲染->组件已挂载->渲染
constructor() {
console.log("构造函数");
super();
// 动态页面用state保存状态
this.state = {
// pokemons: ["皮卡丘", "杰尼龟", "小火龙"],
pokemons: [], // 设置为空解决: <li key={pokemon.url}> warning key pro
egg: "潜龙"
}
}
// 先加载轮廓在填充数据
componentDidMount() {
console.log("组件已挂载");
fetch("https://pokeapi.co/api/v2/pokemon")
.then(res => res.json())
.then(json => {
// 直接改对象属性没有效果
// this.state.pokemons = json.results;
console.log(json.results);
// this.setState({
// pokemons: json.results
// });
// console.log(this.state); // setState是浅更新,只更新该更新的,其余保留
this.setState(
() => {
return {pokemons: json.results}
},
() => {
console.log(this.state); // 上边的回调结束后此行才会调用,也可以证明是浅更新
}
);
})
}
render() {
console.log("渲染")
return (
<div>
<h1>宝可梦</h1>
<input type="search"/>
<ul>
{
// map 页面后来才加载的li,所以页面从静态到动态
// pokemons.map(pokemon=> <li>{pokemon}</li>)
// 动态
this.state.pokemons.map(pokemon => <li key={pokemon.url}>{pokemon.name}</li>)
}
</ul>
</div>
)
}
}
root.render(<App/>)
</script>
</body>
</html>