在Redux Reducer或组件的ShouldComponentUpdate中进行深度比较吗?

编程入门 行业动态 更新时间:2024-10-08 06:19:45

在Redux Reducer或<a href=https://www.elefans.com/category/jswz/34/1771375.html style=组件的ShouldComponentUpdate中进行深度比较吗?"/>

在Redux Reducer或组件的ShouldComponentUpdate中进行深度比较吗?

在我的React Redux应用程序中,setInterval()连续调用查询REST API端点的动作创建器this.props.getLatestNews()。在获取API响应(对象数组)后,它将分派一个以响应数组作为有效负载的动作。

反应成分

class Newsfeed extends Component {
    constructor(props) {
        super(props);
        this.state = { ... }
    }

    componentWillMount() {
        this.updateTimer = setInterval(() => { this.props.getLatestNews() }, 1000);
    }

    componentWillUnmount() {
        clearInterval( this.updateTimer );
    }

    shouldComponentUpdate(nextProps, nextState) {
        // Should we do a deep compare of nextProps & this.props, 
        // shallow compare of nextState & thisState?
    }

    render() {
        return ( ... )
    }
}

const mapStateToProps = (state) => ({
    newsfeed: state.newsfeed
});

const mapDispatchToProps = (dispatch) => {
    return {
        getLatestNews: () => dispatch(getLatestNews())
    }
};

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

在reducer中,当前总是更新部分状态,无论是否有任何更改

减速器

export default function newsfeedReducer(state=initialState, action) {
    switch (action.type) {
        case NEWSFEED_RECEIVED:
            // Or should we do the deep compare of `action.payload` with `state.items` here?
            return { ...state, items: action.payload }

        default:
            return state
    }
}

减根剂

...

const rootReducer = combineReducers({
    newsfeed: newsfeedReducer
});

...

在大多数情况下,收到API结果时,Redux存储库中不存在不存在的新项目。

[为了避免不必要地重新渲染React组件,我在考虑对shouldComponentMount()函数中的当前道具和下一个道具进行深度比较,或者对action.payloadstate.items进行深度比较。 ]应该将其替换。

建议在哪里进行深度比较?还是根本不需要?

谢谢!

回答如下:

一般来说,在使用redux时,我们有几种选择可以避免重新渲染。

更多推荐

在Redux Reducer或组件的ShouldComponentUpdate中进行深度比较吗?

本文发布于:2024-05-07 21:00:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757230.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   深度   Redux   Reducer   ShouldComponentUpdate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!