useState(hooks最基础)
- 数组解构 useState
const [count, setCount] = useState(0); // ES6的数组解构的方法
// 即 全等于 ===
let _userState(0);
let count = useState(0);
let setCount = _userState[1];
- useState 不能存在于 条件 判断语句当中
React Hook "useState" is called conditionally.
生命周期函数(类组件中使用)
- componentDidMount 与 componentDidUpdate
// 刚开始渲染的时候--生命周期函数
componentDidMount() {
console.log(`componentDidMount=> You Clicked ${this.state.count},执行了--渲染--时候的生命周期函数`);
}
// 更新的时候--生命周期函数
componentDidUpdate() {
console.log(`componentDidUpdate=> You Clicked ${this.state.count},执行了--更新--时候的生命周期函数`);
}
例图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aEJtNl7F-1622378298863)(Hooks相关的学习.assets/image-20210427195702903.png)]
useEffect(hooks最基础)
- 相当于 : componentDidMount + componentDidUpdate 两个生命周期函数。
useEffect(() => {
// 相当于两个生命周期函数 === componentDidMount + componentDidUpdate
})
- 当数组存在并有值时,如果数组中的任何值发生更改,则每次渲染后都会触发回调。
- 当它不存在时,每次渲染后都会触发回调。
- 当它是一个空列表时,回调只会被触发一次,类似于 componentDidMount。
- useEffect 是异步函数,不会影响视图更新。
- useEffect 函在件清除 effect 创建的资源时,需要返回一个清除函数:
useEffect(() => {
const subscription = props.soure.subscribe();
return () => {
// 清除函数
subscription.unsubscribe();
}
})
为了防止内存泄漏,清除函数会在组件卸载前执行。另外,如果组件多次渲染,则执行下一个 effect 之前,上一个 effect 就已经被清除。
这就意味着每次更新都会创建新的订阅。
生命周期函数 – 挂载
1、componentWillMount 将要装载,在render之前调用;
componentDidMount,(装载完成),在render之后调用
2、componentWillMount 每一个组件render之前立即调用;
componentDidMount render之后并不会立即调用,而是所有的子组件都render完之后才可以调用
3、componentWillMount 可以在服务端被调用,也可以在浏览器端被调用;
componentDidMount 只能在浏览器端被调用,在服务器端使用react的时候不会被调用