加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react-redux学习笔记

发布时间:2020-12-15 07:39:08 所属栏目:百科 来源:网络整理
导读:本文针对React+Redux实例中的shouldComponentUpdate函数做一个理解, shouldComponentUpdate(nextProps) { return nextProps.state != this.props.state;} 如果state是一个对象,使用这种表示也是正确的,我们从reducer开始理解。 // apple basket reducerex

本文针对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({},{
                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({},{
                isPicking: false
            });
            return newState;

        case 'apple/EAT_APPLE':
            newState = Object.assign({},{
                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函数的更新。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读