本文針對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;
}
};
從上面程式碼可以看出,reducer
中state
如果沒有匹配到action
,state
是沒有更新的,也就是說在shouldComponentUpdate
函式中,nextProps.state
是沒有更新的,即nextProps.state != this.props.state
返回false
, shouldComponentUpdate
函式也就不更新了。
如果有一個action
匹配了,那麼返回的newState與原來的state就不同了,導致了shouldComponentUpdate
函式的更新。