为什么需要类组件(class)?
1.需要状态(state)
2.需要生命周期函数
3.需要副作用操作(ajax)
然而Hooks可以实现以上的语法塘
Hooks的API
useState
const [ count, setCount ] = useState(0)创建一个count的状态,默认值是0,改变count状态的用setCount(这个名字可以随意修改)
每次调用useState时候分配一个空间给状态值的保存,而,react是通过useState的调用顺序辨别各个空间
state不能进行判断增加,顺序会变化,如:
const Counter = () => {
const [ count, setCount ] = useState(0);
if (count === 0){
const [ name, setName ] = useState('momo');} const [ sex, setSex ] = useState('女');
}第一次调用时候,react会分配三个空间存放,count值改变以后,就只有两个空间的值,这个时候去拿name,就会拿到sex的值
useEffect
componentDidmount componentDidUpdate
useEffect(() => {
// 每次mount或者update都会调用
})
componentDidmount
useEffect(() => {
// 只有mount调用
},[])componentWillUnMount
useEffect(() => {
// 只有mount调用
return () => {
// componentWillUnMount
}
},[])componentDidUpdate
const mounted = useRef();
useEffect = (() => {
if(!mounted.current){
mounted.current = true;
} else {
// componentDidUpdate
})useEffect的第二个参数是依赖的数据,如果数组数据变化就再执行,不变化就不执行
useContext
...
hooks和所有HOC都有一样的命名规则useXXX;
每次执行都有独立的props和state