@aks-dev/use-model
v1.0.20
Published
状态管理
Downloads
59
Readme
[step-1]安装
$ npm install @aks-dev/use-model --save
or
$ yarn add @aks-dev/use-model
[step-2]创建全局状态(useAppModel.ts)
import { createAppModel, AppModel } from '@aks-dev/use-model'
type Props = {
backgroundColor: string;
count:number;
name:string;
}
export let initValue: Partial<Props> = {
backgroundColor: 'pink',
count:-1
}
export const useAppModel: AppModel<Props> = createAppModel(initValue)
[step-3]创建单页状态(useViewModel.ts)
import React, { Context } from 'react'
import { createViewModel, ViewModel } from '@aks-dev/use-model'
type P = {
backgroundColor: string;
count: number;
name: string;
}
export const initValue: Partial<P> = {
backgroundColor: 'pink',
count: -10000
}
export const useViewModel = <T>(state?: T): ViewModel<T & P> => createViewModel(Object.assign(initValue, state))
type Prop<T> = {
viewModel: T & P,
setViewModel: (intent: Partial<T & P>) => void
}
export const createContext = <S, T>(): Context<Partial<S> & Prop<T & P>> => React.createContext<Partial<S> & Prop<T & P>>({} as any)
export const useContext = <S, T>(context: React.Context<Partial<S> & Prop<T & P>>) => React.useContext<Partial<S> & Prop<T & P>>(context)
eg:
- import { Provider ,useAppModel} from '@aks-dev/use-model'
export default (props) => {
return (
<Provider {...props} />
)
}
const { model, setModel, initModel } = useAppModel.data
const { model, setModel } = useAppModel()
const { model, setModel } = useAppModel(({model})=>[model.backgroundColor])
- import {createViewModel,createContext,useContext} from '@aks-dev/use-model'
const {setViewModel,viewModel} = useViewModel<Props>()