effect Hook

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }

  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

當(dāng)我們想要在每次render之后執(zhí)行時在class組件中需要在commponentDidMount和componentDidUpdate中都調(diào)用事件。
而在hook中就只需要在useEffect中調(diào)用就可以:

import { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

useEffectHooks視作componentDidMount、componentDidUpdate和componentWillUnmount的結(jié)合。useEffect會在每次render之后調(diào)用。
當(dāng)不需要清理時可以直接:

useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

當(dāng)需要清理時(如定時器)需要返回一個函數(shù):

useEffect(() => {
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

注意:
useEffect的第二個參數(shù)必須傳空數(shù)組,這樣它就等價于只在componentDidMount的時候執(zhí)行。如果不傳第二個參數(shù)的話,它就等價于componentDidMount和componentDidUpdate

import React, { useEffect } from 'react'
?
export function BusinessComponent() {
  const initData = async () => {
    // 發(fā)起請求并執(zhí)行初始化操作
  }
  // 執(zhí)行初始化操作,需要注意的是,如果你只是想在渲染的時候初始化一次數(shù)據(jù),那么第二個參數(shù)必須傳空數(shù)組。
  useEffect(() => {
    initData();
  }, []);
?
  return (<div></div>);
} 

但是有時候我們想在用戶輸入新的id時再進(jìn)行查詢和處理操作我們可以在useEffect中傳入第二個參數(shù),那么就只有在第二個參數(shù)發(fā)生變化(首次渲染)的時候才會觸法effects.

import React, { useEffect } from 'react'
?
export function QRCode(url, userId) {
  // 根據(jù)userId查詢掃描狀態(tài)
  const pollingQueryingStatus = async () => {
  }
?
  const stopPollingQueryStatus = async() => {
  }
  // 我們只是將useEffect的第二個參數(shù)加了個userId
  useEffect(() => {
    pollingQueryingStatus();
?
    return stopPollingQueryStatus;
  }, [userId]);
?
  // 根據(jù)url生成二維碼
  return (<div></div>)
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 知行格-英雄之旅 日精進(jìn)第 29 日 日閱讀:《紅與黑》八章 日鍛煉:無 日總結(jié)反思: 1.我不可能讀完所有的書...
    巖松不姓李不姓白閱讀 207評論 0 4
  • 一見傾心二見愁, 兩步柔情三步行。 畫師難畫佳人眉, 詩者易詠楊柳風(fēng)。
    陌蘇12598閱讀 275評論 0 0
  • 一句雞湯:今天對生活的種種不滿,都源于曾經(jīng)的不努力。 大概意思如此,具體的表述實在記不清了。 自研究生入學(xué)以來,一...
    日月之約閱讀 471評論 0 0
  • 圖片鏈接 活動連接
    田禾繪畫閱讀 228評論 0 1

友情鏈接更多精彩內(nèi)容