如何避免在React-Redux连接的组件中重新渲染?

时间:2018-11-25 06:21:51

标签: reactjs redux

我有react-redux组件SideBar.js,该组件正在订阅redux状态。当redux状态更改时,即使未在redux中订阅该更改状态,该组件也会不必要地重新呈现。由于我的状态是嵌套状态,因此我不想在shouldComponentUpdate()中进行深层比较以避免重新渲染...如何避免额外的重新渲染?

const mapStateToProps = (state) => {
    return {
        guestLogin:{
            status : state.guestLogin.status,
            marketPlace:state.guestLogin.marketPlace,
            newsFeed:state.guestLogin.newsFeed
        },
        accountLogin:{
            showMemberPosts:state.accountLogin.showMemberPosts,
            newsFeed: state.accountLogin.newsFeed,
            marketPlace:state.accountLogin.marketPlace,
            userInfo:state.accountLogin.userInfo
        },
        marketPlace:{
            reset:state.marketPlace.reset,
            disableFilters:state.marketPlace.disableFilters,
            filters:state.marketPlace.filters,


        }

    };
};

const mapDispatchToProps = dispatch => {
    return {
        guestMarketPlaceClickHandler :()=>{dispatch(marketPlaceCLickHandlerDispatcher())},
        guestNewsFeedClickHandler:()=>{dispatch(newsFeedClickHandlerDispatcher())},
        memberMarketPlaceClickHandler:()=>{dispatch(marketPlaceCLickHandlerDispatcher())},
        memberNewsFeedClickHandler:()=>{dispatch(newsFeedClickHandlerDispatcher())},
        myPostsClickHandler:()=>{dispatch(myPostsClickHandlerDispatcher());},
        dispatch:(action)=>{dispatch(action)}
    }
};

export default connect(mapStateToProps,mapDispatchToProps)((SideBar));

1 个答案:

答案 0 :(得分:0)

将组件连接到redux使其成为PureComponent。也就是说,它将对道具进行浅表比较,以决定是否需要重新渲染。通过将商店值嵌套在guestLogin: {...}中,可以保证浅表比较失败。

也就是说,reselect每次都会为guestLogin的值创建一个新对象。

您可以使用const mapStateToProps = (state) => { return { glStatus : state.guestLogin.status, glMarketPlace:state.guestLogin.marketPlace, glNewsFeed:state.guestLogin.newsFeed alShowMemberPosts:state.accountLogin.showMemberPosts, alNewsFeed: state.accountLogin.newsFeed, alMarketPlace:state.accountLogin.marketPlace, alUserInfo:state.accountLogin.userInfo mpReset:state.marketPlace.reset, mpDisableFilters:state.marketPlace.disableFilters, mpFilters:state.marketPlace.filters, }; }; 或同等解决方案来创建在状态不变的情况下返回相同对象的选择器,或者仅使mapStateToProps变浅,例如。

Pattern pattern = Pattern.compile(Pattern.quote(word), Pattern.CASE_INSENSITIVE);