标签:app ntb timer return 列表 end extend 操作 imp
import React, { Component } from ‘react‘
import ReactDOM from ‘react-dom‘
export default class App extends Component {
state = {
count:0
}
componentDidMount(){
this.timer = setInterval(() => {
this.setState(state=>({count:state.count+1}))
}, 1000);
}
componentWillUnmount(){
clearInterval(this.timer)
}
unmount = ()=>{
ReactDOM.unmountComponentAtNode(document.getElementById(‘root‘))
}
render() {
return (
<div>
<h2>当前求和为:{this.state.count}</h2>
<button onClick={this.unmount}>点我卸载组件</button>
</div>
)
}
}
具体实现:
import React from ‘react‘
import ReactDOM from ‘react-dom‘
export default function App(){
// 数组第一个参数为state要保存的值,第二个为操作state的方法,useState()的参数为state的初始值
const [count, setCount] = React.useState(0)
//第一个参数为生命周期钩子函数,第二个参数为要检测的状态列表,如果状态发生改变则调用钩子函数
React.useEffect(()=>{
const timer = setInterval(() => {
setCount(count=>count+1)
}, 1000);
return ()=>{//这个返回的函数会在组件将要卸载时调用,相当于componentWillUnmount()
clearInterval(timer)
}
},[])//空数组表示不检测任何状态,此时相当于componentDidMount(),否则还相当于componentDidUpdate()
function unmount(){
ReactDOM.unmountComponentAtNode(document.getElementById(‘root‘))
}
return (
<div>
<h2>当前求和为:{count}</h2>
<button onClick={unmount}>点我卸载组件</button>
</div>
)
}
React的Hook函数之React.useState()、React.useEffect()
标签:app ntb timer return 列表 end extend 操作 imp
原文地址:https://www.cnblogs.com/pangqianjin/p/14786323.html