示例詳解react中useState的用法
useState
useState 通過在函數(shù)組件里調(diào)用它來給組件添加一些內(nèi)部 state。React 會在重復渲染時保留這個 state。useState
會返回一對值:當前狀態(tài)和一個讓你更新它的函數(shù),你可以在事件處理函數(shù)中或其他一些地方調(diào)用這個函數(shù)。它類似 class 組件的
this.setState,但是它不會把新的 state 和舊的 state 進行合并。
接下來通過一個示例來看看怎么使用 useState。
有這么一個需求:需要在 iframe 中加載外部網(wǎng)頁。
初始的代碼我們通過 函數(shù)式組件 來實現(xiàn)這個需求,只需要簡單的渲染一個 iframe:
import React, { useState } from 'react'; import styles from './index.less'; function Link(props) { const { match: { params: { link = '' } = {} } = {} } = props; const enCodeUrl = decodeURIComponent(link); const url = enCodeUrl.startsWith('http') ? enCodeUrl : `http://${enCodeUrl}`; return ( <React.Fragment> <iframe title={link} src={url} style={{ width: '100%', height: '100%', verticalAlign: 'top' }} frameBorder="0" /> </React.Fragment> ); } export default Link;
新的需求來了,我們需要給頁面添加一個 loading 效果,實現(xiàn)的方式很簡單,監(jiān)聽 iframe 的 load 事件 來設置loading的開始和結束。
為了實現(xiàn)這個需求,我們需要存放loading的狀態(tài),而函數(shù)式組件是沒有自有狀態(tài)的,我們得改造成 class 組件:
import React from 'react'; import { Spin } from 'antd'; import styles from './index.less'; export default class Link extends React.Component { state = { // 存放loading狀態(tài) iLoading: true, }; linkLoad() { // 更新loading this.setState({ iLoading: false }); } render() { const { match: { params: { link = '' } = {} } = {} } = this.props; const { iLoading } = this.state; const enCodeUrl = decodeURIComponent(link); const url = enCodeUrl.startsWith('http') ? enCodeUrl : `http://${enCodeUrl}`; return ( <React.Fragment> <Spin spinning={iLoading} wrapperClassName={styles['iframe-loading']}> <iframe onLoad={this.linkLoad.bind(this)} title={link} src={url} style={{ width: '100%', height: '100%', verticalAlign: 'top' }} frameBorder="0" /> </Spin> </React.Fragment> ); } }
為了實現(xiàn)一個頁面的loading,我們需要去使用class,同時還需要bind綁定this等繁瑣行為,這只是一個簡單的需求,而我們卻可以通過hooks來解決這些問題,同時還能解決組件間狀態(tài)復用的問題,我們使用useState來實現(xiàn)。
導入 useState import React, { useState } from 'react'; 定義狀態(tài) // useState 的參數(shù)為狀態(tài)初始值,setInitLoading為變更狀態(tài)值的方法 const [initLoading, setInitLoading] = useState(true); 更新狀態(tài) onLoad={() => setInitLoading(false)} 完整代碼如下: import React, { useState } from 'react'; import { Spin } from 'hzero-ui'; import styles from './index.less'; function Link(props) { const { match: { params: { link = '' } = {} } = {} } = props; const [initLoading, setInitLoading] = useState(true); const enCodeUrl = decodeURIComponent(link); const url = enCodeUrl.startsWith('http') ? enCodeUrl : `http://${enCodeUrl}`; return ( <React.Fragment> <Spin spinning={initLoading} wrapperClassName={styles['iframe-loading']}> <iframe onLoad={() => setInitLoading(false)} title={link} src={url} style={{ width: '100%', height: '100%', verticalAlign: 'top' }} frameBorder="0" /> </Spin> </React.Fragment> ); } export default Link;
下面看看useState注意事項
useState 的參數(shù)
useState 的參數(shù)可以是基本類型,也可以是對象類型,在更新對象類型時,切記要合并舊的狀態(tài),否則舊的狀態(tài)會丟失
const [params, setParams] = useState({ rotate: 0, color: "#000000" }); const handleInputChange = event => { const target = event.target; setParams({ ...params, [target.name]: target.value }); };
狀態(tài)依賴
如果當前的狀態(tài)需要根據(jù)最后一次更新的狀態(tài)的值計算出來,則給更新狀態(tài)的函數(shù)傳遞一個函數(shù),此函數(shù)的第一個參數(shù)即為最后一次更新的值,然后把計算后的結果做為返回值返回出去。
總結
利用 useState hook 可以讓函數(shù)式組件擁有狀態(tài)管理特性,它與傳統(tǒng)的 class 組件的狀態(tài)管理類似,但是更加簡潔,不用頻繁的使用 this。在后面的文章中將會介紹到如何結合其他的 hooks 對業(yè)務邏輯進行抽離以使組件代碼和 hooks 代碼各司其職。