当前位置: 首页 > Web前端 > HTML

新的React状态库:基于redux和react-redux的foca

时间:2023-03-28 02:02:29 HTML

仓库地址:github.com/foca-js/foca文档地址:foca.js.orgideaTS首先,没有TS就没有编程!特性模块化开发专注typescript极致体验模型自动注册、导出可使用内置immer快速处理数据智能跟踪异步函数执行状态模型支持私有方法可定制多引擎数据持久化数据隔离允许同状态库共存架构图在线演示CodeSandBox使用定义模型//File:counterModel.tsimport{defineModel}from'foca';constinitialState:{count:number}={count:0,};//无需手动注册存储,直接export到react使用exportconstcounterModel=defineModel('counter',{//初始值,必填属性,其他属性可选initialState,actions:{//state可以自动提示type{count:number}plus(state,value:number,double:boolean=false){//直接修改状态state.count+=value*(double?2:1);},minus(state,value:number){//直接返回新状态return{count:state.count-value};},//私有方法,只能被模型内部的effect方法调用,外部调用TS会报错(属性不存在)_clear(state){returnthis.initialState;},},effects:{//异步函数,自动跟踪执行状态(加载)asyncdoSomething(){//调用私有方法awaitthis._sleep(100);//快速处理状态,非常方便网络请求数据this.setState({count:1});this.setState((state)=>{state.count+=1;});//调用动作函数处理状态this.plus(1,true);//调用效果函数returnthis.通用工具(1);},//公共函数commonUtil(x:number){returnx+1;},//私有方法,只能在模型内部使用,如果在外部调用,TS会报错(属性不存在)_sleep(duration:number){returnnewPromise((resolve)=>{setTimeout(resolve,期间);});},},hooks:{//store初始化完成后触发onInithookonInit(){this.plus(1);console.log(this.state);},},});在函数组件中使用import{FC,useEffect}from'react';从'foca'导入{useModel,useLoading};从“./counterModel”导入{counterModel};constApp:FC=()=>{//计数类型自动提示数字const{count}=useModel(counterModel);//只有effects的异步函数可以作为参数传入,其他函数TS会自动报错constloading=useLoading(counterModel.doSomething);useEffect(()=>{counterModel.doSomething();},[]);返回(counterModel.plus(1)}>{count}{loading?'正在加载...':null}

);};exportdefaultApp;在类组件中使用import{Component}from'react';import{connect,getLoading}from'foca';import{counterModel}from'./counterModel';typeProps=ReturnType;classAppextendsComponent{componentDidMount(){counterModel.doSomething();}render(){const{count,loading}=this.props;return(counterModel.plus(1)}>{count}{loading?'Loading...':null}
);}};constmapStateToProps=()=>{return{count:counterModel.state.count,loading:getLoading(counterModel.doSomething);};}导出默认连接(mapStateToProps)(App);希望成为您下一个项目的状态管理解决方案!喜欢就先star仓库地址:https://github.com/foca-js/foca