react中的hook
hook的使用规则
- 函数组件中使用hook,不能再class组件中使用
- 普通的函数中也不能hook
- 循环条件中使用hook
hook
- useState
- useEffect
函数组件一定要大驼峰命名法
const Example: React.FC = () => {
return (
<>
Example
</>
)
}
点我看视频教程,少走弯路
useState hook的用法
const Example: React.FC = () => {
const [count, setCount] = useState<number>(0)
return (
<>
<h1> count的值{count}</h1>
<br />
<Button type='primary' onClick={() => { setCount(count + 1) }}>点击加1</Button>
</>
)
}
对比class组件和函数组件,看hook勾入了哪些生命周期
class组件的声明周期
interface IState {
count: number
}
class Example1 extends Component<any, IState>{
constructor(props: any) {
super(props)
this.state = {
count: 0
}
}
add = () => {
this.setState((state) => ({
count: state.count + 1
}))
}
// 加载完成
componentDidMount() {
document.title = 'Example1:click ' + this.state.count + ' times'
}
// 这件更新了state
componentDidUpdate() {
document.title = 'Example1:click ' + this.state.count + ' times'
}
render() {
return (
<>
<h1>count的值 {this.state.count}</h1>
<br />
<Button type='primary' onClick={this.add}>点击加1</Button>
</>
)
}
}
hook中简单了很多 useState 初始化hook 然后 在useEffect 勾入生命周期
const Example: React.FC = () => {
const [count, setCount] = useState<number>(0)
// 勾入了组件的声明周期
useEffect(() => {
document.title = 'click ' + count + ' times'
})
return (
<>
<h1> count的值{count}</h1>
<br />
<Button type='primary' onClick={() => { setCount(count + 1) }}>点击加1</Button>
</>
)
}
副作用hook的问题
// 函数组件 开头要大写
const Example: React.FC = () => {
const [count, setCount] = useState<number>(0)
const timer = setInterval(() => {
setCount(count + 1)
}, 1000)
// 勾入了组件的声明周期
useEffect(() => {
document.title = 'click ' + count + ' times'
})
return (
<>
<h1> count的值{count}</h1>
<br />
<Button type='primary' onClick={() => { setCount(count + 1) }}>点击加1</Button>
</>
)
}
如何解决hook产生的问题
const Example: React.FC = () => {
const [count, setCount] = useState<number>(0)
const timer = setInterval(() => {
setCount(count + 1)
}, 1000)
// 勾入了组件的声明周期
useEffect(() => {
document.title = 'click ' + count + ' times'
// 在这里勾入了我们组件卸载的生命周期
return () => {
clearInterval(timer)
}
})
return (
<>
<h1> count的值{count}</h1>
<br />
<Button type='primary' onClick={() => { setCount(count + 1) }}>点击加1</Button>
</>
)
}
返回一个清除副作用的函数
useEffect(() => {
document.title = 'click ' + count + ' times'
// 在这里勾入了我们组件卸载的生命周期
return () => {
clearInterval(timer)
}
})
在class组件中如何处理
class Example1 extends Component<any, IState>{
constructor(props: any) {
super(props)
this.state = {
count: 0
}
}
private timer: any
add = () => {
this.setState((state) => ({
count: state.count + 1
}))
}
// 加载完成
componentDidMount() {
document.title = 'Example1:click ' + this.state.count + ' times'
this.timer = setInterval(() => {
this.setState((state) => ({
count: state.count + 1
}))
}, 1000)
}
// 这件更新了state
componentDidUpdate() {
document.title = 'Example1:click ' + this.state.count + ' times'
}
componentWillUnmount() {
clearInterval(this.timer)
}
render() {
return (
<>
<h1>count的值 {this.state.count}</h1>
<br />
<Button type='primary' onClick={this.add}>点击加1</Button>
</>
)
}
}