由于前段時間在領(lǐng)導(dǎo)的“威逼利誘”下,了解和學(xué)習(xí)了下Recoil蔗草,剛開始是比較抗拒的,不過后來慢慢的了解了之后咒精,發(fā)現(xiàn)還是很不錯的镶柱,所以做一個學(xué)習(xí)的筆記和分享模叙。
Recoil最重要的因為它是基于Immutable的數(shù)據(jù)流管理方案歇拆,帶來的可預(yù)測性非常利于調(diào)試和維護:
1.斷點調(diào)試時可預(yù)測范咨,已創(chuàng)建過的值不會突變,與斷點位置也無關(guān)
2.在React框架下組件更新機制單一只有引用變化才觸發(fā)重新渲染输吏,沒有forceUpdate的困擾
上手使用
1.初始化:使用Recoil的狀態(tài)的組件需要用RecoilRoot包裹
import React from 'react';
import {
RecoilRoot,
atom,
selector,
useRecoilState,
useRecoilValue,
useSetRecoilState
} from 'recoil';
function App() {
return (
<RecoilRoot>
<CharacterCounter />
</RecoilRoot>
);
}
2.定義狀態(tài):不需要集中定義替蛉,可以像Mobx分散在各個地方
export const nameState = atom({
key: 'nameState',
default: 'test'
});
其中key在recoliRoot中是唯一的拄氯,并且提供一個默認值它浅,默認值可以是靜態(tài)值、函數(shù)艇纺、異步函數(shù)等
3.訂閱和更新狀態(tài):三個常用API
1). useRecoilState:類似useState的一個Hook邮弹,能夠取到Atom的值以及setter函數(shù)
2). useSetRecoilState:只獲取setter函數(shù)蚓聘,如果只是使用了這個函數(shù),狀態(tài)更新并不會引起組件重新渲染
3). useRecoilValue:只獲取狀態(tài)
import { nameState } from './store'
// useRecoilState
const NameInput = () => {
const [name, setName] = useRecoilState(nameState);
const onChange = (event) => {
setName(event.target.value);
};
return <>
<input type="text" value={name} onChange={onChange} />
<div>Name: {name}</div>
</>;
}
// useRecoilValue
const SomeOtherComponentWithName = () => {
const name = useRecoilValue(nameState);
return <div>{name}</div>;
}
// useSetRecoilState
const SomeOtherComponentThatSetsName = () => {
const setName = useSetRecoilState(nameState);
return <button onClick={() => setName('Jon Doe')}>Set Name</button>;
}
4.派生狀態(tài):與Mobx的computed類似与纽,selector表示一段派生狀態(tài)塘装,提供了get、set蹦肴、分別定義如何賦值,如何取值勺阐,同時其與atom定義的一樣可以使用上述三種API矛双。
const lengthState = selector({
key: 'lengthState',
get: ({get}) => {
const text = get(nameState);
return text.length;
},
});
function NameLength() {
const length = useRecoilValue(lengthState);
return <>Name Length: {length}</>;
}
5.異步狀態(tài):基于selector可以實現(xiàn)異步數(shù)據(jù)讀取,即修改get函數(shù)為異步函數(shù)
const userNameQuery = selector({
key: 'userName',
get: async ({get}) => {
const response = await myDBQuery({
userID: get(currentUserIDState),
});
return response.name;
},
});
function CurrentUserInfo() {
const userName = useRecoilValue(userNameQuery);
return <div>{userName}</div>;
}
function MyApp() {
return (
<RecoilRoot>
<ErrorBoundary>
<React.Suspense fallback={<div>Loading...</div>}>
<CurrentUserInfo />
</React.Suspense>
</ErrorBoundary>
</RecoilRoot>
);
}
其中懒闷,異步狀態(tài)可以被Suspense捕獲栈幸,異步過程報錯可以被ErrorBoundary捕獲。
如果不想用Suspense異步阻塞侦镇,可以使用useRecoilValueLoadable在當前組件內(nèi)管理異步狀態(tài)
不足
- Immutable壓力:API繁多,而且Immutable模式中震捣,對于數(shù)據(jù)流只有讀和寫兩種訴求,但是我們期待讀的含義是蒿赢,UI能夠在訂閱其變化后自然而然Rerender。
Recoil提供了useRecoilState作為讀寫雙重API壹若,useRecoilValue只是簡化了API皂冰,但是useSetRecoilValue在僅寫不讀的場景下,是不會隨著狀態(tài)變更重新渲染組件的秃流。
對比useState,他是單組件狀態(tài)管理的場景概说,但Recoil是全局狀態(tài)解決方案嚣伐,讀寫分離的場景下糖赔,對于只寫的組件很有必要脫離對數(shù)據(jù)的訂閱實現(xiàn)性能最大化轩端。 - 條件訪問數(shù)據(jù):因為Hooks的通病放典,無法寫在條件語句中船万,所以要利用 Hooks 獲取一個帶有條件判斷的數(shù)據(jù)時,必須回到 selector 模式耿导。
從useRecoilState以及selector來看,相當于Recoil對useContext和useMemo的封裝舱呻。
收獲
盡管短時間內(nèi)我們不會在項目上Recoil,但是它帶給我們的絕不只是上述的用法芥驳,在狀態(tài)管理上茬高,我們或許可以思考新的出發(fā)點:
- 讀與寫分離兆旬,做到最優(yōu)按需渲染
- 派生的值必須嚴格緩存怎栽,并在命中緩存時引用保證嚴格相等
- 原子存儲的數(shù)據(jù)相互無關(guān)聯(lián)宿饱,所有關(guān)聯(lián)的數(shù)據(jù)都使用派生值方式推導(dǎo)