第一
export default function App() {
const [name,setname] = useState('huhu')
useEffect(()=>{
setname(name.substring(0,1).toUpperCase()+name.substring(1))
},[name])
//[name,age]//可以有多个参数
//带参数,第一次默认执行一次,第二次name更新也会执行
return (
<div>
app={name}
<button onClick={()=>{
setname('xiaoming')
}}>
click
</button>
</div>
)
}
第二
import React, { Component, useEffect } from 'react'
export default class App extends Component {
state = {
isCreate : true
}
render() {
return (
<div>
<button onClick={()=>{
this.setState({
isCreate:!this.state.isCreate
})
}}>点击</button>
{/* { this.state.isCreate?<Child />:'' } */}
{ this.state.isCreate && <Child /> }
</div>
)
}
}
function Child(props){
useEffect(()=>{
window.onresize = ()=>{
console.log('resize')
}
var timer = setInterval(() => {
console.log(1234)
}, 1000);
// 点击之后只执行一次
return()=>{
console.log('组件销毁')
window.onresize = null;
clearInterval(timer)
}
},[])
return <div>
child
</div>
}