react-hooks的基本使用
1 class组件
- 引入Component
- 组件基础component
- 导出组件类
1.1 state
import React, { Component } from 'react';
class CountDemo extends Component {
constructor(props) {
super(props);
this.state = { count:0 }
}
render() {
return (
<>
<p>you click { this.state.count} times!</p>
<button onClick={this.btnClick.bind(this)}>Click me!</button>
</>
);
}
btnClick(){
this.setState({
count:this.state.count+1
})
}
}
export default CountDemo;
出现的问题:
- 变量的引用麻烦,需要添加this.state
- 方法的引用需要注意绑定作用域
1.2 生命周期
import React, { Component } from 'react';
class CountDemo extends Component {
constructor(props) {
super(props);
this.state = { count:0 }
}
componentDidMount(){
console.log(`componentDidMount->${this.state.count}`)
}
componentDidUpdate(){
console.log(`componentDidUpdate->${this.state.count}`)
}
render() {
return (
<>
<p>you click { this.state.count} times!</p>
<button onClick={this.btnClick.bind(this)}>Click me!</button>
</>
);
}
btnClick(){
this.setState({
count:this.state.count+1
})
}
}
export default CountDemo;
- 出现问题
两个生命周期里面编写重复代码。
生命周期:
- 挂载卸载过程
- constructor(props, context)
- componentWillMount()
- componentDidMount()
- componentWillUnmount()
- 更新过程
- componentWillReceiveProps(nextProps)
- shouldComponentUpdate(nextProps,nextState)
- componentWillUpdate(nextProps,nextState)
- componentDidUpadate(prevProps,prevState)
- render()
2 function组件[react-hooks]
- 引入定义状态的方法(useState)
- 引入其他hook处理
- 导出组件函数
2.1 state=>useState
定义状态变量使用 useState
:(进行值初始化,并拥有一个重新定义值的方法)
const [count,setCount] = useState(0)
所以,以上的例子可以简写为
import React, { useState } from 'react';
function CountDemo(){
const [count,setCount] = useState(0)
return(
<>
<p>you click { count} times!</p>
<button onClick={()=>{setCount(count+1)}}>Click me!!!</button>
</>
)
}
export default CountDemo
注意:useState 根据定义顺序,来确定各个状态的key,所以不能把状态放在if语句里面。
if(true){
const [name,setName] = useState('rhlee')
}
/*
报错如下:
React Hook "useState" is called conditionally.
React Hooks must be called in the exact same order in every component render
*/
2.2 生命周期=>useEffect
useEffect
Hook 相当于:
componentDidMount
,componentDidUpdate
和componentWillUnmount
这三个函数的组合。
- useEffect()
- 函数体:
componentDidMount
,componentDidUpdate
- 返回值:
componentWillUnmount
- 函数体:
useEffect(() => {
// 执行组件挂载完成/组件更新完成的生命周期
console.log(`componentDidUpdate->${this.state.count}`)
// Specify how to clean up after this effect:
return function cleanup() {
// 清除引用的变量,计时器等的清除。
};
});