当你写react的时候还在为什么时候用有状态的组件和无状态的组件而烦恼时,react16.8出的hooks解决了这个问题。
这里放出官方中文文档
当然你也可以不用hooks也可以只用class 但是我觉得hooks是趋势
State Hook
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>
);
}
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>
);
}
}
对比两行代码就会很好理解this.setState()被我们setCount代替了,我们要设置count的值直接在setCount调用就可以了
乍一看很简单如果我们state多了可能会遇到
const [recommendation, setValue3] = useState('');
const [error1, setError1] = useState(false);
const [helperText1, setHelperText1] = useState('');
const [error2, setError2] = useState(false);
const [helperText2, setHelperText2] = useState('');
const [error3, setError3] = useState(false);
const [helperText3, setHelperText3] = useState('');
这样看起来会有点头晕,其实我们依然可以像之前一样
const [state, setState] = useState({
open: false,
vertical: 'top',
horizontal: 'center',
});
调用的时候把state传过去
setState(state => ({ ...state, open: true }));
Effect Hook
官方解释的很好
你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。
这样我们就没有看起来很复杂的生命周期了
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
在useEffect中直接变为
useEffect(() => {
document.title = `You clicked ${count} times`;
});
跟生命周期一样useEffect第一次渲染之后和每次更新之后都会执行
你会发现我们还有componentWillUnmount这个生命周期如果卸载一些状态拿在useEffect中应该怎么办呢
我们只需要每次在effect中返回一个清除函数
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
我们Hook 需要在我们组件的最顶层调用
不能再条件语句中使用hooks
if (name !== '') {
useEffect(function persistForm() {
localStorage.setItem('formData', name);
});
}