示例詳解react中useState的用法
useState
useState 通過在函數(shù)組件里調(diào)用它來給組件添加一些內(nèi)部 state。React 會(huì)在重復(fù)渲染時(shí)保留這個(gè) state。useState
會(huì)返回一對(duì)值:當(dāng)前狀態(tài)和一個(gè)讓你更新它的函數(shù),你可以在事件處理函數(shù)中或其他一些地方調(diào)用這個(gè)函數(shù)。它類似 class 組件的
this.setState,但是它不會(huì)把新的 state 和舊的 state 進(jìn)行合并。
接下來通過一個(gè)示例來看看怎么使用 useState。
有這么一個(gè)需求:需要在 iframe 中加載外部網(wǎng)頁(yè)。
初始的代碼我們通過 函數(shù)式組件 來實(shí)現(xiàn)這個(gè)需求,只需要簡(jiǎn)單的渲染一個(gè) 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;
新的需求來了,我們需要給頁(yè)面添加一個(gè) loading 效果,實(shí)現(xiàn)的方式很簡(jiǎn)單,監(jiān)聽 iframe 的 load 事件 來設(shè)置loading的開始和結(jié)束。
為了實(shí)現(xiàn)這個(gè)需求,我們需要存放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> ); } }
為了實(shí)現(xiàn)一個(gè)頁(yè)面的loading,我們需要去使用class,同時(shí)還需要bind綁定this等繁瑣行為,這只是一個(gè)簡(jiǎn)單的需求,而我們卻可以通過hooks來解決這些問題,同時(shí)還能解決組件間狀態(tài)復(fù)用的問題,我們使用useState來實(shí)現(xiàn)。
導(dǎo)入 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注意事項(xiàng)
useState 的參數(shù)
useState 的參數(shù)可以是基本類型,也可以是對(duì)象類型,在更新對(duì)象類型時(shí),切記要合并舊的狀態(tài),否則舊的狀態(tài)會(huì)丟失
const [params, setParams] = useState({ rotate: 0, color: "#000000" }); const handleInputChange = event => { const target = event.target; setParams({ ...params, [target.name]: target.value }); };
狀態(tài)依賴
如果當(dāng)前的狀態(tài)需要根據(jù)最后一次更新的狀態(tài)的值計(jì)算出來,則給更新狀態(tài)的函數(shù)傳遞一個(gè)函數(shù),此函數(shù)的第一個(gè)參數(shù)即為最后一次更新的值,然后把計(jì)算后的結(jié)果做為返回值返回出去。
總結(jié)
利用 useState hook 可以讓函數(shù)式組件擁有狀態(tài)管理特性,它與傳統(tǒng)的 class 組件的狀態(tài)管理類似,但是更加簡(jiǎn)潔,不用頻繁的使用 this。在后面的文章中將會(huì)介紹到如何結(jié)合其他的 hooks 對(duì)業(yè)務(wù)邏輯進(jìn)行抽離以使組件代碼和 hooks 代碼各司其職。
相關(guān)文章
React路由中的redux和redux知識(shí)點(diǎn)拓展
這篇文章主要介紹了React路由中的redux和redux知識(shí)點(diǎn)拓展,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的朋友可以參考學(xué)習(xí)一下2022-08-08react實(shí)現(xiàn)動(dòng)態(tài)表單
這篇文章主要為大家詳細(xì)介紹了react實(shí)現(xiàn)動(dòng)態(tài)表單,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08React實(shí)現(xiàn)全局組件的Toast輕提示效果
這篇文章主要介紹了React實(shí)現(xiàn)全局組件的Toast輕提示效果,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-09-09基于React實(shí)現(xiàn)搜索GitHub用戶功能
在本篇博客中,我們將介紹如何在 React 應(yīng)用中搜索 GitHub 用戶并顯示他們的信息,文中通過代碼示例給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-02-02React文件名和目錄規(guī)范最佳實(shí)踐記錄(總結(jié)篇)
React在使用時(shí)非常靈活,如果沒有一個(gè)規(guī)范約束項(xiàng)目,在開發(fā)過程中會(huì)非?;靵y,本文將介紹幾個(gè)優(yōu)秀的規(guī)范,介紹文件名和目錄前,需要先簡(jiǎn)述一下幾種通用的類型,用來區(qū)分文件的功能,感興趣的朋友一起看看吧2022-05-05ReactNative實(shí)現(xiàn)的橫向滑動(dòng)條效果
本文介紹了ReactNative實(shí)現(xiàn)的橫向滑動(dòng)條效果,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),補(bǔ)充介紹了ReactNative基于寬度變化實(shí)現(xiàn)的動(dòng)畫效果,感興趣的朋友跟隨小編一起看看吧2024-02-02React 數(shù)據(jù)獲取條件競(jìng)爭(zhēng)原理解析
這篇文章主要為大家介紹了React 數(shù)據(jù)獲取條件競(jìng)爭(zhēng)原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01