useState
- 使用狀態(tài)
const [n, setN] = React.useState(0)
const [user, setUser] = React.useState({name: 'Jack', age: 18})
- 注意事項(xiàng)1: 不可局部更新
如果state是一個(gè)對(duì)象,能否部分setState?
答案是不行,因?yàn)閟etState不會(huì)幫我們合并屬性
那么useReducer會(huì)合并屬性嗎?也不會(huì)!
因?yàn)镽eact認(rèn)為這應(yīng)該是你自己要做的事情
function App(){
const [user, setUser] = React.useState({name: 'Jack', age: 18})
const onClick = () =>{
//setUser不可以局部更新,如果只改變其中一個(gè),那么整個(gè)數(shù)據(jù)都會(huì)被覆蓋
// setUser({
// name: 'Frank'
// })
setUser({
...user, //拷貝之前的所有屬性
name: 'Frank' //這里的name覆蓋之前的name
})
}
return (
<div className='App'>
<h1>{user.name}</h1>
<h2>{user.age}</h2>
<button onClick={onClick}>Click</button>
</div>
)
}
- 注意事項(xiàng)2: 地址要變
setState(obj) 如果obj地址不變,那么React就認(rèn)為數(shù)據(jù)沒有變化,不會(huì)更新視圖
useState 續(xù)
- useState接受函數(shù)
const [state, setState] = useState(() => {return initialState})
該函數(shù)返回初始state,且只執(zhí)行一次
- setState接受函數(shù)
setN(i => i + 1)
如果你能接受這種形式,應(yīng)該優(yōu)先使用這種形式
useReducer
- 用來踐行Flux/Redux思想
看代碼,分四步走
一、創(chuàng)建初始值initialState
二、創(chuàng)建所有操作reducer(state, action);
三、傳給userReducer,得到讀和寫API
四、調(diào)用寫({type: '操作類型'})
總的來說,useReducer 是 useState 的復(fù)雜版
如何代替 Redux
- 步驟
一、將數(shù)據(jù)集中在一個(gè) store 對(duì)象
二、將所有操作集中在 reducer
三、創(chuàng)建一個(gè) Context
四、創(chuàng)建對(duì)數(shù)據(jù)的讀取 API
五、將第四步的內(nèi)容放到第三步的 Context
六、用 Context.Provider 將 Context 提供給所有組件
七、各個(gè)組件用 useContext 獲取讀寫API
import React, { useReducer, useContext, useEffect } from "react";
import ReactDOM from "react-dom";
const store = {
user: null,
books: null,
movies: null
};
function reducer(state, action) {
switch (action.type) {
case "setUser":
return { ...state, user: action.user };
case "setBooks":
return { ...state, books: action.books };
case "setMovies":
return { ...state, movies: action.movies };
default:
throw new Error();
}
}
const Context = React.createContext(null);
function App() {
const [state, dispatch] = useReducer(reducer, store);
const api = { state, dispatch };
return (
<Context.Provider value={api}>
<User />
<hr />
<Books />
<Movies />
</Context.Provider>
);
}
function User() {
const { state, dispatch } = useContext(Context);
useEffect(() => {
ajax("/user").then(user => {
dispatch({ type: "setUser", user: user });
});
}, []);
return (
<div>
<h1>個(gè)人信息</h1>
<div>name: {state.user ? state.user.name : ""}</div>
</div>
);
}
function Books() {
const { state, dispatch } = useContext(Context);
useEffect(() => {
ajax("/books").then(books => {
dispatch({ type: "setBooks", books: books });
});
}, []);
return (
<div>
<h1>我的書籍</h1>
<ol>
{state.books ? state.books.map(book => <li key={book.id}>{book.name}</li>) : "加載中"}
</ol>
</div>
);
}
function Movies() {
const { state, dispatch } = useContext(Context);
useEffect(() => {
ajax("/movies").then(movies => {
dispatch({ type: "setMovies", movies: movies });
});
}, []);
return (
<div>
<h1>我的電影</h1>
<ol>
{state.movies
? state.movies.map(movie => <li key={movie.id}>{movie.name}</li>)
: "加載中"}
</ol>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
// 幫助函數(shù)
// 假 ajax
// 兩秒鐘后,根據(jù) path 返回一個(gè)對(duì)象,必定成功不會(huì)失敗
function ajax(path) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (path === "/user") {
resolve({
id: 1,
name: "Frank"
});
} else if (path === "/books") {
resolve([
{
id: 1,
name: "JavaScript 高級(jí)程序設(shè)計(jì)"
},
{
id: 2,
name: "JavaScript 精粹"
}
]);
} else if (path === "/movies") {
resolve([
{
id: 1,
name: "愛在黎明破曉前"
},
{
id: 2,
name: "戀戀筆記本"
}
]);
}
}, 2000);
});
}
useContext
- 上下文
全局變量是全局的上下文
上下文是局部的全局變量
- 使用方法
一、使用 C = createContext(initial) 創(chuàng)建上下文
二、使用 <C.Provider> 圈定作用域
三、在作用域內(nèi)使用 useContext(C)來使用上下文
useEffect
- 副作用 (API 名字叫得不好)
對(duì)環(huán)境的改變即為副作用,如修改 document.title
但我們不一定非要把副作用放在 useEffect 里面
實(shí)際上叫做 afterRender 更好,每次render后執(zhí)行
- 用途
一、作為 componentDidMount 使用,[ ] 作第二個(gè)參數(shù)
二、作為 componentDidUpdate 使用,可指定依賴
三、作為 componentWillUnmount 使用,通過 return
四、以上三種用途可同時(shí)存在
- 特點(diǎn)
如果同時(shí)存在多個(gè) useEffect, 會(huì)按照出現(xiàn)次序執(zhí)行
useLayoutEffect
- 布局副作用
useEffect 在瀏覽器渲染完成后執(zhí)行
useLayoutEffect 在瀏覽器渲染前執(zhí)行
function App1() {
const [n, setN] = useState(0)
const time = useRef(null)
const onClick = () => {
setN(i => i + 1)
time.current = performance.now()
}
useLayoutEffect(() => {
if (time.current) {
console.log(performance.now() - time.current) //大概是0.7ms
}
})
useEffect(() => {
if (time.current) {
console.log(performance.now() - time.current) //大概是2.7ms
}
})
return (
<div className="App">
<h1>n: {n}</h1>
<button onClick={onClick}>Click</button>
</div>
);
}
- 特點(diǎn)
useLayoutEffect 總比 useEffect 先執(zhí)行
useLayoutEffect 里的任務(wù)最好影響了 Layout
/* useLayoutEffect比useEffect先執(zhí)行 */
function App2() {
const [n, setN] = useState(0)
const onClick = () => {
setN(i => i + 1)
}
//執(zhí)行順序打印出 2、3、1
useEffect(() => {
console.log(1)
})
useLayoutEffect(() => {
console.log(2)
})
useLayoutEffect(() => {
console.log(3)
})
return (
<div className="App">
<h1>n: {n}</h1>
<button onClick={onClick}>Click</button>
</div>
);
}
- 經(jīng)驗(yàn)
為了用戶體驗(yàn),優(yōu)先使用 useEffect (優(yōu)先渲染)
useMemo
- 要理解 React.useMemo
需要先講 React.memo
React默認(rèn)有多余的render
function App() {
const [n, setN] = React.useState(0);
const [m, setM] = React.useState(0);
const onClick = () => {
setN(n + 1);
};
return (
<div className="App">
<div>
{/*點(diǎn)擊button會(huì)重新執(zhí)行Child組件*/}
<button onClick={onClick}>update n {n}</button>
</div>
<Child data={m}/>
{/* <Child2 data={m}/> */}
</div>
);
}
function Child(props) {
console.log("child 執(zhí)行了");
console.log('假設(shè)這里有大量代碼')
return <div>child: {props.data}</div>;
}
const Child2 = React.memo(Child);
將代碼中的 Child 用React.memo(Child) 代替
如果 props 不變,就沒有必要再次執(zhí)行一個(gè)函數(shù)組件
最終代碼:
function App() {
const [n, setN] = React.useState(0);
const [m, setM] = React.useState(0);
const onClick = () => {
setN(n + 1);
};
return (
<div className="App">
<div>
{/*點(diǎn)擊button會(huì)重新執(zhí)行Child組件*/}
<button onClick={onClick}>update n {n}</button>
</div>
<Child data={m}/>
</div>
);
}
const Child = React.memo(props => {
console.log("child 執(zhí)行了");
console.log('假設(shè)這里有大量代碼')
return <div>child: {props.data}</div>;
});
- 但是
這玩意有一個(gè)bug
添加了監(jiān)聽函數(shù)之后,一秒破功因?yàn)?App 運(yùn)行時(shí),會(huì)再次執(zhí)行 onClickChild,生成新的函數(shù)
新舊函數(shù)雖然功能一樣,但是地址引用不一樣!
function App() {
const [n, setN] = React.useState(0);
const [m, setM] = React.useState(0);
const onClick = () => {
setN(n + 1);
};
const onClickChild = () => {}
return (
<div className="App">
<div>
{/*點(diǎn)擊button會(huì)重新執(zhí)行Child組件*/}
<button onClick={onClick}>update n {n}</button>
</div>
{/*但是如果傳了一個(gè)引用,則React.memo無效。因?yàn)橐檬遣幌嗟鹊?/}
<Child data={m} onClick={onClickChild}/>
</div>
);
}
//使用React.memo可以解決重新執(zhí)行Child組件的問題
const Child = React.memo(props => {
console.log("child 執(zhí)行了");
console.log('假設(shè)這里有大量代碼')
return <div onClick={props.onClick}>child: {props.data}</div>;
});
怎么辦? 用useMemo:
function App() {
const [n, setN] = React.useState(0);
const [m, setM] = React.useState(0);
const onClick = () => {
setN(n + 1);
};
const onClick1 = () => {
setM(m + 1);
};
const onClickChild = () => {}
const onClickChild1 = useMemo(() => {
return () => {
console.log(`on click child m: ${m}`)
}
}, [m])
return (
<div className="App">
<div>
{/*點(diǎn)擊button會(huì)重新執(zhí)行Child組件*/}
<button onClick={onClick}>update n {n}</button>
<button onClick={onClick1}>update m {m}</button>
</div>
{/*但是如果傳了一個(gè)引用,則React.memo無效。因?yàn)橐檬遣幌嗟鹊?/}
{/*<Child data={m} onClick={onClickChild}/>*/}
{/*onClickChild1使用useMemo可以消除此bug*/}
<Child data={m} onClick={onClickChild1}/>
</div>
);
}
//使用React.memo可以解決重新執(zhí)行Child組件的問題
const Child = React.memo(props => {
console.log("child 執(zhí)行了");
console.log('假設(shè)這里有大量代碼')
return <div onClick={props.onClick}>child: {props.data}</div>;
});
useMemo
- 特點(diǎn)
第一個(gè)參數(shù)是 () => value
第二個(gè)參數(shù)是依賴 [m, n]
只有當(dāng)依賴變化時(shí),才會(huì)計(jì)算出新的 value
如果依賴不變,那么就重用之前的 value
這不就是 Vue 2的 computed 嗎?
- 注意
如果你的 value 是一個(gè)函數(shù),那么你就要寫成useMemo(() => x => console.log(x))
這是一個(gè)返回函數(shù)的函數(shù)
是不是很難用?于是就有了useCallback
useCallback
- 用法
useCallback(x => console.log(x), [m]) 等價(jià)于
useMemo( () => x => console.log(x), [m])
forwardRef
- useRef
可以用來引用 DOM 對(duì)象
也可以用來引用普通對(duì)象
- forwardRef
props 無法傳遞 ref 屬性
function App(){
const buttonRef = useRef(null)
return (
<div>
<Button ref={buttonRef}>按鈕</Button>
{/* 控制臺(tái)報(bào)錯(cuò):
Warning: Function components cannot be given refs.
Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?
*/}
</div>
)
}
const Button = (props) => {
console.log(props) // {ref: undefined, children: "按鈕"}
return <button {...props} />
}
實(shí)現(xiàn) ref 的傳遞:由于 props 不包含 ref,所以需要 forwardRef
import React, {forwardRef, useRef} from 'react';
function App(){
const buttonRef = useRef(null)
return (
<div>
<Button ref={buttonRef}>按鈕</Button2>
</div>
)
}
const Button = forwardRef((props, ref) => {
console.log(ref) //可以拿到ref對(duì)button的引用,forwardRef僅限于函數(shù)組件,class 組件是默認(rèn)可以使用 ref 的
return <button ref={ref} {...props} />;
})
自定義 Hook
- 封裝數(shù)據(jù)操作
簡(jiǎn)單例子
// useList.js
import {useState, useEffect} from 'react'
const useList = () => {
const [list, setList] = useState(null)
useEffect(() => {
ajax().then(list => {
setList(list)
})
}, []) //確保只在第一次運(yùn)行
return {
list,
setList
}
}
export default useList
function ajax(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([
{id: 1, name: 'Frank'},
{id: 2, name: 'Jack'},
{id: 3, name: 'Alice'},
{id: 4, name: 'Bob'},
{id: 5, name: 'Han'}
])
}, 1000)
})
}
//index.js
import useList from './hooks/useList'
function App(){
const {list, setList} = useList()
return (
<div>
<h1>List</h1>
{
list ? (
<ol>
{
list.map(item => {
return <li key={item.id}>{item.name}</li>
})
}
</ol>
):(
'加載中...'
)
}
</div>
)
}
貼心例子
// useList.js
import {useState, useEffect} from 'react'
const useList = () => {
const [list, setList] = useState(null)
useEffect(() => {
ajax().then(list => {
setList(list)
})
}, []) //確保只在第一次運(yùn)行
return {
list,
addItem: name => {
setList([...list, {id: Math.random(), name}])
},
deleteIndex: index => {
setList(list.slice(0, index).concat(list.slice(index + 1)))
}
}
}
export default useList
function ajax(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([
{id: 1, name: 'Frank'},
{id: 2, name: 'Jack'},
{id: 3, name: 'Alice'},
{id: 4, name: 'Bob'},
{id: 5, name: 'Han'}
])
}, 1000)
})
}
//index.js
import useList from './hooks/useList'
function App() {
const {list, deleteIndex} = useList()
return (
<div>
<h1>List</h1>
{
list ? (
<ol>
{
list.map((item,index) => {
return (
<li key={item.id}>
{item.name}
<button
onClick={() => {
deleteIndex(index);
}}
>
x
</button>
</li>
)
})
}
</ol>
) : (
'加載中...'
)
}
</div>
)
}
- 分析
你還可以在自定義 Hook 里使用 Context
useState 只說了不能在 if 里,沒說不能在函數(shù)里運(yùn)行,只要這個(gè)函數(shù)在函數(shù)組件里運(yùn)行即可
自定義 Hook 完全可以代替 Redux