redux核心步驟

概念

redux是一種架構模式,能夠和react、vue結合使用。vue

解決的問題

優雅地修改共享數據狀態,避免狀態在父子組件的連鎖改動(子組件多的話改起來麻煩)及外部改動形成的沒必要要(難以排除)問題,因此全部的改動強橫經過一個方法(dispatch)修改。react

clipboard.png

實現步驟

//state(數據)和action(控制修改)後的數據
function reducer (state, action) {
    /!* 初始化 state 和 switch case *!/
}

// 經過reducer獲取state
// 執行action
// 監聽數據變化
const store = createStore(reducer)

// 監聽數據變化從新渲染頁面
// 經過觀察者模式監聽數據變化,避免沒有狀態改變的頻繁渲染
store.subscribe(() => renderApp(store.getState()))

// 首次渲染頁面
renderApp(store.getState())

示例

const usersReducer = (state, action) => {
    if (!state) return [];
    switch (action.type) {
        case "ADD_USER":
            return [...state, action.user]
        case "DELETE_USER":
            return [...state.slice(0, action.index), ...state.slice(action.index + 1)]
        case "UPDATE_USER":
            let user = {
                ...state[action.index],
                ...action.user,
            }
            return [
                ...state.slice(0, action.index),
                user,
                ...state.slice(action.index + 1),
            ]
        default:
            return state
    }
}
//state(數據)和dispatch(控制修改)封裝起來
function createStore (reducer) {
    let state = null
    const listeners = []
    const subscribe = (listener) => listeners.push(listener)
    const getState = () => state
    const dispatch = (action) => {
        state = reducer(state, action) // 覆蓋原對象
        // console.log(listeners)
        listeners.forEach((listener) => {
            // console.log(listener)
            listener()

        })
    }
    dispatch({}) // 初始化 state
    return { getState, dispatch, subscribe }
}
const store = createStore(usersReducer);
console.log(store.getState());
//增
store.dispatch({
    type: 'ADD_USER',
    user: {
        username: 'Lucy',
        age: 12,
        gender: 'female'
    }
});
console.log(store.getState());
//改
store.dispatch({
    type: 'UPDATE_USER',
    index: 0,
    user: {
        username: 'Tomy',
        age: 12,
        gender: 'male'
    }
});
console.log(store.getState());
//刪
store.dispatch({
    type: 'DELETE_USER',
    index: 0 // 刪除特定下標用戶
});
console.log(store.getState());
參考文獻 React.js 小書
相關文章
相關標籤/搜索