react-redux学习笔记
文章目录
本文针对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函数的更新。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论