安装
首先,安装一下 @wokeyi/store 这个库
$ yarn add @wokeyi/store
或者
$ npm install @wokeyi/store
使用
使用方法和 redux-react-hook 类似,但是不依赖于 redux
创建一个实例
import { create } from '@wokeyi/store'
const reducer = (prevState, action) => {
return prevState + action
}
// create 接受一个 reducer 和 初始值(非必传)
const { useStore, useDispatch, StoreProvider } = create(reducer, 2)
export {
useStore,
useDispatch,
StoreProvider,
}
在使用的组件外层包裹 StoreProvider
const App = () => {
return (
<StoreProvider store={1}>
<Child/>
</StoreProvider>
)
}
export default App
使用数据和派发 action
使用数据时用 useStore 就可以,用 dispatch 来派发一个 action
const Child: React.FC = props => {
const value = useStore()
const dispatch = useDispatch()
const add = React.useCallback(() => {
dispatch(4)
}, [])
return (
<div>
<p>{value}</p>
<button onClick={add}>add</button>
</div>
)
};
export default Child
其他
上面是一个简单的数值状态,同样可以传入一个复杂的 reducer
const reducer = (prevState, action) => {
switch (action.type) {
case 'SET_NAME':
return {
...prevState,
name: action.name,
}
case 'SET_AGE':
return {
...prevState,
age: action.age,
}
default:
return prevState
}
}
上面 reducer 中 action 的类型为
type ActionType = {
type: 'SET_NAME'
name: string
} | {
type: 'SET_AGE',
age: number
}
那么在派发 action 的时候,就是下面这种形式的用法了
const Child: React.FC = () => {
const store = useStore()
const dispatch = useDispatch()
const setAge = React.useCallback(() => {
// 提供一个 type 和更新的字段值
dispatch({
type: 'SET_AGE',
age: store.age + 1,
})
}, [store.age])
return (
<button onClick={setAge}>
set age
</button>
)
}
export default Child
大小
整个库大小不到 1 KB,如图所示
Github 地址为 github.com/wokeyi/reac…
如果感觉不错,可以点个 Star