Attention:Hooks are a new addition in React 16.8.
所以使用 Hooks 時要注意一下 React 的版本哦。
1. CodeSandBox的使用
使用 CodeSandBox 可以在線創(chuàng)建 React 應用。
小技巧:
- 創(chuàng)建了 React 應用后,需修改版本號時可直接在
package.json里修改,并保存,就會自動加載了。 - 命令行面板上 輸入
npm info react versions可查詢 React 版本。
2. useState 的使用
首先要引入 useState:
import {useState} from "react"
useState 的使用:
const [state, setState] = useState(initialState);
其中,state表示state的值;setState表示更新 state 的函數;useState返回一個數組,數組的第一項表示state的值;initialState表示 state 的初始值。
示例代碼:
function App() {
const [count, setCount] = useState(0)
const add = ()=>{
setCount(count + 1)
}
const minus = ()=>{
setCount(count - 1)
}
return (
<div className="App">
<div>
<span className="value">{count}</span>
</div>
<button onClick={add}>加1</button>
<button onClick={minus}>減1</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
原本函數組件是沒有狀態(tài)的,但自從有了 Hooks,函數組件可以有狀態(tài)了。
3. useState的更多例子
function App() {
const [user, setUser] = useState({
name: "janice",
age: 18,
hobbies: ["reading", "game", "coding", "basketball"]
});
const addHobbies = () => {
let newHobbies = Math.random();
setUser({
...user,
hobbies: [...user.hobbies, newHobbies]
});
};
const delHobbies = () => {
user.hobbies.splice(1, 1);
setUser({
...user,
hobbies: user.hobbies
});
};
return (
<div className="App">
<div>
{user.name} , {user.age}
</div>
<div>{user.hobbies.join(" , ")}</div>
<button onClick={addHobbies}>增加愛好</button>
<button onClick={delHobbies}>刪除愛好</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
4. useEffect的使用
使用 useEffect 處理副作用,下面舉例說明一下什么是副作用:
function f1() {} // f1是沒作用的函數
function f2() { // f2是有副作用的函數
console.log(1)
}
function f3(a, b) { // f3是純函數,又稱沒有副作用的函數
return a + b
}
- 在 函數
f2中,依賴了console.log(1), 依賴的東西可能會被修改,有可能會產生意外的結果。
依賴了不知從哪來的東西的函數就是有副作用的函數。 - 函數
f3是純函數,又稱沒有副作用的函數,即不依賴外部不知從哪來的東西。
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
//把有副作用的函數放在useEffect里
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}