HOOKS勾子/ESLint Plugin/練習REACT

X13QQ
X13QQ
Published in
2 min readDec 21, 2020

HOOKS勾子

基本的 Hooks

  • useState ‒ 可在函式型元件中使用 state(狀態)
  • useEffect ‒ 可在函式型元件中使用生命周期方法
  • useContext ‒ 可在函式型元件中使用 Context API

Hooks 可以透過上述的內建 Hooks,再自訂出針對特定需定的 Hooks,但 Hooks 都是以 use 開頭的函式, 例如 useFetch、usePromise、useArray 等等

Hooks使用

  • Hooks 可以在不更動元件階層的情況下重覆利用狀態的邏輯
  • Hooks 可以拆分一個元件功能到小的幾個函式中

當功能愈來愈複雜時,元件的程式碼難以維護和拆分

元件的生命周期有可能會有相當複雜的應用情況,有各種不同的副作用與狀態邏輯,很容易造成 bugs 或不連續性的問題

  • Hooks 可以讓開發者使用大部份的 React 功能,但不需要使用類別

Hooks基本準則

  • React 函式型元件中呼叫 Hooks (以大駝峰命名的函式‒PascalCase function)
  • 在其它自訂的 Hooks 中呼叫 Hooks (以 use 開頭命名的函式)

ESLint Plugin

# npm 
npm install eslint-plugin-react-hooks --save-dev
# yarn
yarn add eslint-plugin-react-hooks --dev

設定 .eslintrc

{ 
“plugins”: [
// …
“react-hooks”
],
“rules”: {
// …
“react-hooks/rules-of-hooks”: “error”,
“react-hooks/exhaustive-deps”: “warn”
}
}

計數器練習

React計數器

勾子App.js

import React, { useState } from 'react' function App() {  
const [total, setTotal] = useState(0)

return <h1 onClick={() => setTotal(total + 1)}>{total}</h1>
}
export default App

類別型元件App.js

import React from 'react'class App extends React.Component {
constructor() {
super()
this.state = {
total: 0, //init value
}
}
render() {
return (
<h1
onClick={() => {
this.setState({ total: this.state.total + 1 })
}}
>
{this.state.total}
</h1>
)
}
}
export default App

JS計數器

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="total">0</h1>

<script src="index.js"></script>
</body>
</html>

index.js

const total = document.getElementById('total') total.addEventListener('click', function(event){    
total.innerHTML = +total.innerHTML + 1
})

擴充工具

除錯

Redux DevTools

React Developer Tools

--

--