Although one of them is writing code with react recently, but I don’t use hooks very much, I just write native code and life cycle. I have nothing to do today, let’s take a look at react-hook and find that using hook, I don’t want to use life cycle anymore. It is found that useEffect directly replaces the life cycle.
Look at the code, here is the example
<!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">
<title>react-function-hook</title>
</head>
<body>
<div id="app"></div>
<script src='./lib//babel.min.js'></script>
<script src='./lib/react.development.js'></script>
<script src='./lib//react-dom.development.js'></script>
<script type="text/babel">
const { Component, useState, useEffect } = React
// function 定义的组件不存在this指向问题
// useEffect 意思是副作用,接收两个参数(()=>{设定的set参数处理函数}, [依赖项])。
// (参数一表示处理函数/回调函数,参数二表示依赖项由数组组成,当依赖内容发生改变后,第一个处理函数会执行;如果是空数组表示只有在组件初始化时执行),
function App() {
// 一个页面可以写多个useState
const [ params1, setParams1 ] = useState([])
const [ count, setCount ] = useState(0)
const [ msg, setMsg ] = useState('')
// 第二个参数是空的数组,那么这个在初始化的时候执行一次,
useEffect(()=>{
fetch('url')
.then(res=>res.json())
.then(data=>setParams1(data.datas))
})
useEffect(()=>{
setMsg('count的值为:' + count) // 第一个参数叫做处理函数
},[count]) // 第二个参数是依赖项
return (
<div className="app">
{params1.map(item=>(
<p key={item.id}>{item.name}</p>
))}
<button onClick={()=>setCount(count+1)}>当前的计数值为:{count}</button>
<h2>{msg} useEffect用来代替生命周期</h2>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('app'))
</script>
</body>
</html>
The effect diagram is as follows