class方式componentDidMount、componentWillUnmount、componentDidUpdate生命周期函数
import React from 'react';
export default class App extends React.Component {
state = {
count:0,
size:[window.innerWidth,window.innerHeight]
};
onResize = ()=>{
this.setState({
size:[window.innerWidth,window.innerHeight]
});
}
componentDidMount(){
console.log("组件挂载后调用");
document.title=this.state.count;
window.addEventListener("resize",this.onResize,false);
}
componentWillUnmount(){
console.log("组件卸载后调用");
window.removeEventListener("resize",this.onResize,false);
}
componentDidUpdate(){
console.log("组件更新后调用");
document.title=this.state.count;
}
render() {
const {count} = this.state;
const [width,height] = this.state.size;
return (
<button
type="button"
onClick={()=>{this.setState({count:count+1})}}
>
Click({count})
size:{width}x{height}
</button>
);
}
}
effect hook方式
import React , {useEffect, useState} from 'react';
export default function App(){
const [count,setCount] = useState(0);
const [size,setSize] = useState([window.innerWidth,window.innerHeight]);
onResize = ()=>{
setSize([window.innerWidth,window.innerHeight]);
}
useEffect(()=>{ //相当于componentDidMount、componentDidUpdate
console.log('组件渲染后执行,每次都执行');
document.title=count;
});
useEffect(()=>{ //相当于componentDidMount、omponentWillUnmount
console.log('组件渲染后执行,只执行一次'); //因为添加了[]数组,所以只会执行一次
window.addEventListener("resize",onResize,false);
return ()=>{ // 返回回调函数,做清理副作用操作
console.log('组件卸载后执行,只执行一次');
window.removeEventListener("resize",onResize,false);
}
},[]);
useEffect(()=>{
console.log(`数组里的count发生变化了,就会调用:count:${count}`);
},[count]);
const [width,height] = size;
return (
<button
type="button"
onClick={()=>{setCount(count+1)}}
>
Click({count})
size:{width}x{height}
</button>
);
}
useEffect返回回调函数对上一个effect进行清理操作
import React , {useEffect, useState} from 'react';
export default function App(){
const [count,setCount] = useState(0);
const onClick = ()=>{
console.log('click');
}
useEffect(()=>{
document.querySelector("#size").addEventListener('click',onClick,false);
return ()=>{ // 它会在调用一个新的 effect 之前对前一个 effect 进行清理
document.querySelector("#size").removeEventListener('click',onClick,false);
}
});
return (
<div>
<button
type="button"
onClick={()=>{setCount(count+1)}}
>
Click({count})
</button>
{
count % 2
?<span id="size">点击span</span>
:<p id="size">点击p</p>
}
</div>
);
}