react hooks入門

當(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);
    });
  }

https://react.docschina.org/docs/hooks-rules.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • React是現(xiàn)在最流行的前端框架之一,它的輕量化,組件化,單向數(shù)據(jù)流等特性把前端引入了一個(gè)新的高度,現(xiàn)在它又引入的...
    老鼠AI大米_Java全棧閱讀 5,854評(píng)論 0 26
  • 你還在為該使用無(wú)狀態(tài)組件(Function)還是有狀態(tài)組件(Class)而煩惱嗎?——擁有了hooks,你再也不需...
    米亞流年閱讀 964評(píng)論 0 5
  • React Hook 是React16.8提出來(lái)的一個(gè)新特性,其意義就在于我們可以讓函數(shù)組件變得跟類組件一樣有能力...
    陳曉拉尼閱讀 442評(píng)論 0 0
  • 你還在為該使用無(wú)狀態(tài)組件(Function)還是有狀態(tài)組件(Class)而煩惱嗎?——擁有了hooks,你再也不需...
    水落斜陽(yáng)閱讀 82,468評(píng)論 11 100
  • 主要介紹 useState useEffect useReducer useContext 用法 你還在為...
    叫我蘇軾好嗎閱讀 27,636評(píng)論 3 41

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