React手写redux工作过程,详解redux工作原理

手写redux工作过程,使用class类的方式

为了学习下redux,决定手写一个工作过程来模拟一下,感觉思路还是很简单的。
首先来看一下传统redux的写法:

 import {
    
    legacy_createStore as createStore} from 'redux'

const reducer=(prestate={
     
     
    show:true
},action)=>{
    
    
    var newstate={
    
    ...prestate}
    switch(action.type)
    {
    
    
        case 'hide-tarbar':
            newstate.show=false
            return newstate;
        case 'show-tarbar':
            newstate.show=true
            return newstate
        default:
            return prestate
    }
}

const store = createStore(reducer);
export default store

这个可以很明显看到重点就是这个createStore这个类的方法了,首先是创建一个reducer函数来解决中间的逻辑,然后将参数reducer传给我们的createStore类,这个应该就是一个类的传参效果,然后来看看重点使用的store的三个函数:
subscribe函数和getState函数,获取store相关参数:

componentDidMount(){
    
    
    store.subscribe(()=>{
    
    
      console.log('aaa');
      console.log(store.getState());
      this.setState({
    
    
        show:store.getState().show
      })
    })
  }

需要使用状态以及订阅的函数,通过调用暴露出来的store对象的subscribe和getState方法,来获取对应的参数和处理中间逻辑。
dispatch方法:

import store from '../redux/store'
componentDidMount = () => {
    
    
    console.log('detail-mount');
    store.dispatch({
    
    
      type:'hide-tarbar',
    })
  }

需要改变状态的组件中,使用dispatch来发布改变状态,并且需要传入参数。
到这里我们来总结一下过程,整体上就是一个类叫createStore,然后里面有三个函数dispatch,subscribe和getState函数,然后每次调用store类,需要传入reducer处理函数,对内部进行逻辑处理,所以store就是在做一个中间人的工作,通过dispatch获取到目标改变的type类型,然后传达给我们的reducer,reducer将处理结果返回给store类的状态,同时,dispatch还需要执行所有通过subscribe传递过来的逻辑函数,之后store类通过getState将数据暴露出去,而subscribe函数就是在做一个接受逻辑函数到store内部管理的工作,所以在store内部需要两个变量list[ ](收集逻辑函数),state(初始状态),最后,store将三个方法暴露出去,于是,就是下列的代码:

const reducer=(prestate={
    
        //内部处理函数reducer
    show:true
},action)=>{
    
    
    var newstate={
    
    ...prestate}
    switch(action.type)
    {
    
    
        case 'hide-tarbar':
            newstate.show=false
            return newstate;
        case 'show-tarbar':
            newstate.show=true
            return newstate
        default:
            return prestate
    }
}



class xjdstore
{
    
    
    static list=[]
    static state=reducer(undefined,{
    
    })  //这里将reducer作为外部调用
    static dispatch(action)   //模拟dispatch,接受外界的action参数
    {
    
    
        this.state=reducer(this.state,action);   //调用reducer处理逻辑
        for(var i in this.list)
        this.list[i]&&this.list[i]()   //执行收集到的函数
    }   
    static subscribe(callback)
    {
    
    
        this.list.push(callback)   //收集函数,模拟subscribe
    }
    static getState()
    {
    
    
        return this.state   //模拟getState,返回内部状态
    }
}


export default xjdstore;

在上面的代码中需要注意的就是,由于是类在调用方法,所以所有的数据和成员方法必须是static,这样子才不会报错,store内部可能还会有其他的功能,比如不是所有的dispatch执行时都需要调用所有的list方法,这样子很影响性能,至于如何解决应该不难,可以判断字段啥的都行,但是大模拟基本上是介个样子。
今天的文章就到这里啦!

猜你喜欢

转载自blog.csdn.net/weixin_51295863/article/details/132794489