react hooks - useState 使用

Hook 是 React 16.8 的新增特性。它可以讓你在不編寫 class 的情況下使用 state 以及其他的 React 特性。

useState

useState 通過在函數組件里調用它來給組件添加一些內部 state。React 會在重復渲染時保留這個 state。useState 會返回一對值:當前狀態(tài)和一個讓你更新它的函數,你可以在事件處理函數中或其他一些地方調用這個函數。它類似 class 組件的 this.setState,但是它不會把新的 state 和舊的 state 進行合并。

接下來通過一個示例來看看怎么使用 useState。

有這么一個需求:需要在 iframe 中加載外部網頁。

初始的代碼我們通過 函數式組件 來實現這個需求,只需要簡單的渲染一個 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 效果,實現的方式很簡單,監(jiān)聽 iframe 的 load 事件 來設置loading的開始和結束。

為了實現這個需求,我們需要存放loading的狀態(tài),而函數式組件是沒有自有狀態(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>
    );
  }
}

為了實現一個頁面的loading,我們需要去使用class,同時還需要bind綁定this等繁瑣行為,這只是一個簡單的需求,而我們卻可以通過hooks來解決這些問題,同時還能解決組件間狀態(tài)復用的問題,我們使用useState來實現。

  1. 導入 useState
import React, { useState } from 'react';
  1. 定義狀態(tài)
  // useState 的參數為狀態(tài)初始值,setInitLoading為變更狀態(tài)值的方法
  const [initLoading, setInitLoading] = useState(true);
  1. 更新狀態(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 使得我們的代碼更加輕便,同時更容易理解和閱讀。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容