Effect Hook 可以让你在函数组件中执行副作用操作(用于模拟类组件中的生命周期钩子),可以把useEffect Hook看做 componentDidMount() 、componentDidUpdate()、componentWillUnmount()三个函数的组合 官方文档说明:使用Effect Hook 语法说明
React.useEffect(()=>{
return ()=>{
},[setValue])
示例
import React, { Component } from "react";
import ReactDOM from 'react-dom'
function Demo() {
console.log("demo");
const [count, setCount] = React.useState(0);
React.useEffect(()=>{
let timer=setInterval(() => {
setCount(count=>count+1)
}, 1000);
return ()=>{
clearInterval(timer)
}
},[])
function add() {
setCount((count) => count + 1);
}
function unmount(){
ReactDOM.unmountComponentAtNode(document.getElementById('root'))
}
return (
<div>
<h2>当前求和为:{count}</h2>
<button onClick={add}>点我+1</button>
<button onClick={unmount}>卸载组件</button>
</div>
);
}
export default Demo;
如果是在类组件中写法如下
import React, { Component } from "react";
import ReactDOM from 'react-dom'
class Demo extends Component {
state = { count: 0 };
add = () => {
this.setState(state=>({count:state.count+1}))
}
componentDidMount(){
this.timer=setInterval(() => {
this.setState(state=>({count:state.count+1}))
}, 1000);
}
unmount=()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('root'))
}
componentWillUnmount(){
clearInterval(this.timer)
}
render() {
return (
<div>
<h2>当前求和为{this.state.count}</h2>
<button onClick={this.add}>点我+1</button>
<button onClick={this.unmount}>卸载组件</button>
</div>
);
}
}
export default Demo;
|