react-redux學習筆記

wscops發表於2016-12-27

本文針對React+Redux例項中的shouldComponentUpdate函式做一個理解,

shouldComponentUpdate(nextProps) {
    return nextProps.state != this.props.state;
}

如果state是一個物件,使用這種表示也是正確的,我們從reducer開始理解。

// apple basket reducer

export default (state = {
    isPicking: false,
    newAppleId: 1,
    apples: [
        {
            id: 0,
            weight: 235,
            isEaten: false
        }
    ]
}, action) => {
    
    let newState ;
    

    switch (action.type) {
        case `apple/BEGIN_PICK_APPLE`:
            newState = Object.assign({}, state, {
                isPicking: true
            });
            return newState;

        case `apple/DONE_PICK_APPLE`:
            newState = Object.assign({}, state, {
                apples: [
                    ...state.apples,
                    {
                        id: state.newAppleId,
                        weight: action.payload,
                        isEaten: false
                    }
                ],
                newAppleId: state.newAppleId + 1,
                isPicking: false
            })
            return newState;

        case `apple/FAIL_PICK_APPLE`:
            //這裡只是簡單處理
            newState = Object.assign({}, state, {
                isPicking: false
            });
            return newState;

        case `apple/EAT_APPLE`:
            newState = Object.assign({}, state, {
                apples: [
                    ...state.apples.slice(0, action.payload),
                    Object.assign({}, state.apples[action.payload], { isEaten: true }),
                    ...state.apples.slice(action.payload + 1)
                ]
            })
            return newState;

        default:
            return state;
    }

};

從上面程式碼可以看出,reducerstate如果沒有匹配到actionstate是沒有更新的,也就是說在shouldComponentUpdate函式中,nextProps.state是沒有更新的,即nextProps.state != this.props.state 返回false, shouldComponentUpdate函式也就不更新了。
如果有一個action匹配了,那麼返回的newState與原來的state就不同了,導致了shouldComponentUpdate函式的更新。