1. 程式人生 > 實用技巧 >react-hook

react-hook

react16.8新增特性,它可以讓你在不編寫class的情況下使用state及其它react特性

hook可取代class的使用

hook產生的原因:
1.解決元件間複用狀態邏輯難的問題

2.複雜元件變得難以理解

hook使用規則:

1.只能在函式最外層呼叫hook,不要在迴圈、條件判斷或子函式中呼叫

2.只能在react得函式元件中呼叫hook。不要在其它JavaScript函式中呼叫。

3.自定義hook中也可以呼叫hook

規範hook使用規則的外掛:

eslint-plugin-react-hooks

"react-hooks/rules-of-hooks": "error", // 檢查 Hook 的規則

"react-hooks/exhaustive-deps": "warn" // 檢查 effect 的依賴

useState用法:

宣告變數:

const [age,setAge]=useState(42)

const [fruit,setFruit]=useState('banana')

const [todos,setTodos] = useState([{text:'學習hook'}])

單獨更新值:

setFruit('orange')

hook與class的對於寫法:

//HOOK寫法

import React, { useState } from 'react';

function
Example() { // 宣告一個叫 "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寫法 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> ); } }

useEffect Hook用法:

useEffect hook可以看作componentDidMount、componentDidUpdate和componentWillUnmount這三個函式的組合。在第一次渲染之後和每次更新之後都會執行

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

自定義hook:

1.必須以use開頭