溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

redux的核心是什么

發(fā)布時(shí)間:2020-12-07 11:09:50 來(lái)源:億速云 閱讀:158 作者:小新 欄目:web開發(fā)

這篇文章給大家分享的是有關(guān)redux的核心是什么的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧。

概念

redux是一種架構(gòu)模式,可以和react、vue結(jié)合使用。

解決的問(wèn)題

優(yōu)雅地修改共享數(shù)據(jù)狀態(tài),避免狀態(tài)在父子組件的連鎖改動(dòng)(子組件多的話改起來(lái)麻煩)及外部改動(dòng)造成的不必要(難以排除)問(wèn)題,所以所有的改動(dòng)強(qiáng)橫通過(guò)一個(gè)方法(dispatch)修改。

redux的核心是什么

實(shí)現(xiàn)步驟

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

// 通過(guò)reducer獲取state
// 執(zhí)行action
// 監(jiān)聽數(shù)據(jù)變化
const store = createStore(reducer)

// 監(jiān)聽數(shù)據(jù)變化重新渲染頁(yè)面
// 通過(guò)觀察者模式監(jiān)聽數(shù)據(jù)變化,避免沒(méi)有狀態(tài)改變的頻繁渲染
store.subscribe(() => renderApp(store.getState()))

// 首次渲染頁(yè)面
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(數(shù)據(jù))和dispatch(控制修改)封裝起來(lái)
function createStore (reducer) {
    let state = null
    const listeners = []
    const subscribe = (listener) => listeners.push(listener)
    const getState = () => state
    const dispatch = (action) => {
        state = reducer(state, action) // 覆蓋原對(duì)象
        // 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 // 刪除特定下標(biāo)用戶
});
console.log(store.getState());

感謝各位的閱讀!關(guān)于redux的核心是什么就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI