當(dāng)你寫react的時(shí)候還在為什么時(shí)候用有狀態(tài)的組件和無(wú)狀態(tài)的組件而煩惱時(shí),react16.8出的hooks解決了這個(gè)問(wèn)題。
這里放出官方中文文檔
當(dāng)然你也可以不用hooks也可以只用class 但是我覺得hooks是趨勢(shì)
State Hook
import React, { useState } from 'react';
function Example() {
// 聲明一個(gè)叫 “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>
);
}
}
對(duì)比兩行代碼就會(huì)很好理解this.setState()被我們setCount代替了,我們要設(shè)置count的值直接在setCount調(diào)用就可以了
乍一看很簡(jiǎn)單如果我們state多了可能會(huì)遇到
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('');
這樣看起來(lái)會(huì)有點(diǎn)頭暈,其實(shí)我們依然可以像之前一樣
const [state, setState] = useState({
open: false,
vertical: 'top',
horizontal: 'center',
});
調(diào)用的時(shí)候把state傳過(guò)去
setState(state => ({ ...state, open: true }));
Effect Hook
官方解釋的很好
你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 這三個(gè)函數(shù)的組合。
這樣我們就沒有看起來(lái)很復(fù)雜的生命周期了
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
在useEffect中直接變?yōu)?/p>
useEffect(() => {
document.title = `You clicked ${count} times`;
});
跟生命周期一樣useEffect第一次渲染之后和每次更新之后都會(huì)執(zhí)行
你會(huì)發(fā)現(xiàn)我們還有componentWillUnmount這個(gè)生命周期如果卸載一些狀態(tài)拿在useEffect中應(yīng)該怎么辦呢
我們只需要每次在effect中返回一個(gè)清除函數(shù)
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
我們Hook 需要在我們組件的最頂層調(diào)用
不能再條件語(yǔ)句中使用hooks
if (name !== '') {
useEffect(function persistForm() {
localStorage.setItem('formData', name);
});
}