TeleState 特性
1、hooks api的状态共享。
2、可在组件外,通过dispatch更改state.
3、无需provider,不用考虑组件是否在provider作用域下。
4、体积仅4k.
5、typescript friendly.
缺点
暂不支持class组件,需自己使用函数式组件进行高阶来进行支持。
无法局部状态共享。如menu组件menu-item共享menu的状态,由于多个menu实例的状态并不相同,则只能使用context+provider方案.
实现原理
通过 setState queue 来分发状态。
安装
npm i tele-state
第一步,创建一个状态联动的 hooks "useTeleState"
src/moduleA/store.ts
import React, { useEffect } from 'react'
import { createTeleState } from 'tele-state'
const { useTeleState } = createTeleState(1)
export {
useTeleState
}
step2 - 在组件中使用该hooks,api与useState类似
src/moduleA/componentTest.tsx
import {useTeleState} from './store'
function ComponentA(){
const [ count ] = useTeleState()
console.log('B----------', count)
return <>{count}</>
}
function ComponentB(){
const [ count, setCount ] = useTeleState()
console.log('A----------', count)
useEffect( () =>{
setCount(count+1) // ComponentA will update too.
}, [] )
return <button onClick={() => setCount(count+1)}>add {count}</button>
}
组件外读取/更改状态
src/store.ts
const {
useTeleState,
dispatch, // 在组件外更改状态,状态同步更新,组件异步渲染.
getState, // 在组件外获取当前状态
} = createTeleState(1)
export const addCount = () => {
// 在组件外更改状态,状态同步更新,组件异步渲染.
dispatch( preCount => preCount+1 )
// 在组件外获取当前状态.
const count = getState()
fetch(`/api/bean?count=${count}`)
}
export {
useTeleState
}
实际项目中,创建多个teleState,每个teleState在各自业务/功能模块下声明状态。后续在项目拆分时,也很容易
与现在主流方案的对比
hooks + context
基本原理是将state与dispatch都保存在context的Provider中,利用useContext api 获取provider中的state与dispatch. 在此基础上的封装则有easy-peasy等。
// 创建context
const countContex = createContext({count: 1, setCount: (count: number) => {}})
// 将dispatch 与 state放入provider
const StoreProvider = ({children}: {children:ReactElement}) => {
const [count, setCount] = useState(1)
return <countContex.Provider value={{count, setCount }}>
{children}
</countContex.Provider>
}
// 使用useContext
const ComponentA = () => {
const { count, setCount} = useContext(countContex)
// ....
}
该方案相对与teleState 缺点:
1、在组件外获取/更新状态不是很方便。
2、在使用状态时,需要考虑Provider的作用域问题.
mobx
当初mobx 的api设计是面向对象的,大量使用装饰器模式。现在hooks使得拥抱函数式组件。显得略显尴尬。在此也不做过多评价
redux
优点:redux规范了数据流。 缺点:对状态管理进行集中管理,不利于懒加载。