手动实现redux

redux是一种架构模式(Flux 架构的一种变种),是 JavaScript 状态容器,提供可预测化的状态管理,可以用在React、Angular、Ember、jQuery 甚至纯 JavaScript,但不能用于vue。

下面是参照网上写的简单实现:

function renderApp(newAppState,oldAppState={}) {
        if(newAppState===oldAppState) return //数据没有变化就不渲染了
        console.log('render app')
        renderTitle(newAppState.title,oldAppState.title)
        renderContent(newAppState.content,oldAppState.content)
    }
    function renderTitle(newTitle,oldTitle) {
        if(newTitle===oldTitle) return
        console.log('render title')
        const titleDom=document.getElementById('title');
        titleDom.innerHTML=newTitle.text;
        titleDom.style.color=newTitle.color;
    }
    function renderContent(newContent,oldContent) {
        if(newContent===oldContent) return
        console.log('render content')
        const contentDom=document.getElementById('content');
        contentDom.innerHTML=newContent.text;
        contentDom.style.color=newContent.color;
    }

    function reducer(state,action){
        if(!state){
            return {
                title:{
                    text:"react.js",
                    color:"red"
                },
                content:{
                    text:"这是内容",
                    color:"green"
                }
            }
        }
        switch (action.type) {
            case 'UPDATE_TITLE_TEXT':
                return{
                    ...state,
                    title:{
                        ...state.title,
                        text:action.text
                    }
                }
                break
            case 'UPDATE_TITLE_COLOR':
                return {
                    ...state,
                    title:{
                        ...state.title,
                        color:action.color
                    }
                }
                break
            default:
                return state //没有修改
        }
    }
    function createStore(reducer){
        let state=null;
        const listeners=[];
        const subscribe= (listener)=>listeners.push(listener)
        const getState=()=>state;
        const dispatch=(action)=>{
            state=reducer(state,action) //重新赋值
            listeners.forEach((listener)=>listener())
        }
        dispatch({}) //初始化state
        return{getState,dispatch,subscribe}
    }


    const store=createStore(reducer)
    let oldState=store.getState();
    store.subscribe(()=>{
        const newState=store.getState();
        renderApp(newState,oldState)
        oldState=newState

    })
    renderApp(store.getState()) //首次渲染初始化
    store.dispatch({type:"UPDATE_TITLE_TEXT",text:"这是修改后的数据"})
    store.dispatch({type:"UPDATE_TITLE_COLOR",color:"orange"})

 参照出处动手实现redux

原文地址:https://www.cnblogs.com/yuanzhiguo/p/11314116.html