an-store v1.0.68
AnStore
一款恰到好处的全局状态管理库
安装
npm install an-store
or
yarn add an-store
快速上手
初始化
export store = new Store({
state: { // 初始化数据
name: 'jack',
age: 36
},
site: 'local',
rootKey: 'myStore'
})
获取状态
store.getState('name')
// => jack
修改状态
store.dispatch('name', 'tom')
重置状态
store.init({name: 'rose', age: 24})
删除状态
store.remove('name')
API
constructor
初始化 store
- state ? Object // 可选 初始化的数据
- site ? string // 可选 缓存的位置,当运行环境为浏览器时,可选值为 'local' | 'session',小程序时不区分且默认存储
- rootKey ? string // 可选 缓存的key
getState
获取状态
- key 状态KEY
dispatch
修改状态
- key string
- value any
clean
清除状态
remove
删除某个状态
- key string
useListen
某个状态发生变化时的HOOK
- effect: Function // 回调函数,当deps数组中某一项状态发生变化时,会将变化后的值当做参数传入,数据结构像这样{item: 'name', pre: 'jack', next: 'tom'}
- item 发生变化的状态KEY
- pre 发生变化之前的数据
- next 发生变化之后的数据
- deps: Array // 依赖项,需要监听的状态KEY
- once: boolean default false // 为true则当依赖项发生变化时只执行一次回调函数就销毁
使用示例:
store.useListen(({item, pre, next}) => {
console.log(item, pre, next)
}, ['name'], true)
unListen
额外的API
connect
- 扩展组件
- 当前组件可以使组件扩展连接其他组件。
- 扩展的组件可以有一个注入的函数集合,注入的函数在源组件中可以使用this调用
扩展的组件需向外暴露一个对象或函数,对象结构如下,如果是函数,则需返回该对象类型
注意;扩展组件必须和外界状态无任何关联,即内部状态不依赖props
注意:源组件必须是函数组件且不能为箭头函数
interface IInject{ widget: React.FC<any> // 组件 injection: { [k: any]: any } // 注入的对象 }
使用:
connect(injects: Array<IInject | (() => IInject)>)(Component: React.FC<any>)
transmit
- 和
use
为组合API - 在
根组件
中将你的store传递下去 - 同时,可以链式调用
globalInjection
来注入你的全局组件
(可选)全局组件:通过
use
API默认注入的组件
在组件中使用 use
API来修饰你的组件,你的组件中即可使用this获取到这些东西
import React from 'react'
import MyRouter from '@router'
import store from '@store'
import { transmit } from 'an-store'
...
...
const rootWidget = transmit(store, <MyRouter />)
// 注入全局组件
rootWidget = rootWidget.globalInjection([{
widget: () => <span>测试注入</span>,
injection: {
add(a, b) {
console.log('这是注入的函数...')
return a + b
}
}
])
// 你的根组件
React.render(rootWidget, document.getElementById("root"))
注意:此API需放在根组件中执行
use
- 和
transmit
为组合API 使用
use
来包装你的组件,在组件中则可以使用this
来获取到通过transmit
传递的store
和全局组件use(Component)
组件中获取store:
this.store.getState('name')
- extra
可以使组件再扩展连接其他组件,连接的扩展组件的对象类型也需符合
IInject
||() => IInject
类型
use(Component).extra([{
widget: () => <span>注入组件</span>
injection: {
add(a, b) {
console.log('注入组件函数')
return a + b
}
}
}])
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago