Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redux 实现原理 #94

Open
hsipeng opened this issue May 12, 2020 · 0 comments
Open

Redux 实现原理 #94

hsipeng opened this issue May 12, 2020 · 0 comments
Labels

Comments

@hsipeng
Copy link
Owner

hsipeng commented May 12, 2020

function createStore(reducer, state = null){
    let listeners = [];
    let getState = () => state;
    let subscribe = listener => listeners.push(listener);
    let dispatch = (action) => {
        state = reducer(state, action);
        listeners.forEach(listener => listener());
    }
    return {
        getState,
        subscribe,
        dispatch
    }
}

const initialState = {
    couter: 0
}

function reduers(state, action){
    if(!state){
        return initialState
    }
    switch(action.type){
        case 'ADD':
            let num = state.couter
            num += action.num;
            return {
                ...state, 
                couter: num
            }
    }
}

const store = createStore(reduers, initialState)

store.subscribe(()=>{
    console.log(`当前state,${JSON.stringify(store.getState())}`)
})
store.dispatch({
    type: 'ADD',
    num: 1
})

store.dispatch({
    type: 'ADD',
    num: 1
})

store.dispatch({
    type: 'ADD',
    num: 1
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant