React Hooks 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。
前言
本篇主要以讲解语法为主。
useState
这个例子用来显示一个计数器。当你点击按钮,计数器的值就会增加,现在我们的写法如下,
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
这是我们所熟悉的写法,替换成useState后
import React, { useState } from 'react';
function Example() {
// 声明一个叫 "count" 的 state 变量
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
- 1.首先通过在函数组件里调用useState()来给组件添加一些内部 state,(React 会在重复渲染时保留这个 state)。
- 2.useState()可以传入一个参数,传入的参数就是初始的state,在上面例子当中,0就是初始值。【这个初始 state 参数只有在第一次渲染的会被用到。】
- 3.useState() 会返回一对值:当前状态和一个让你更新它的函数(你可以在事件处理函数中或其他一些地方调用这个函数,它类似 class 组件的 this.setState,但是它不会把新的 state 和旧的 state 进行合并。)
- 4.可以通过useState声明多个state变量,如下
function ExampleWithManyStates() {
// 声明多个 state 变量!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...
}