Redux-React最佳实践(表演问题)

时间:2017-05-09 14:19:06

标签: javascript reactjs redux react-redux

您是否知道将shouldComponentUpdate与redux

一起使用的正确方法

让我的代码作为示例:

import React from 'react';


@connect((store) => {
    return {
        data: store.Reducer..data,
        labels: store.Reducer.labels,
    };
})
export default class Bar_Comp extends React.Component {
    constructor() {
        super()
    }
    componentWillMount() {

        this.props.dispatch(Action.GetListdata());

        var data = {
            labels: [],
            datasets: [
                {
                    data: []
                }
            ]
        };
        this.setState({ data: data, lastIndex: 1 });

    }
    getElementAtEvent(elemn) {
        if (elemn[0]) {
                .
                .
                .
                this.props.dispatch(Action.action2(datasets[elemn[0]._index - 1], labels[elemn[0]._index - 1]))


        }
    }
        shouldComponentUpdate(nextProps, nextState) {

        if (_.isEmpty(nextProps.labels))
            return false;
        else if (_.isEqual(nextProps.labels, this.props.labels))
            return false;
        return true;

} 
    componentWillReceiveProps(nextProps) {

        if (!_.isEmpty(nextProps.data) && _.isEqual(nextProps.data, this.props.data)) {
            ....

            datasets = functions based on nextProps ...
            labels = functions based on nextProps ...
            this.setState({ data: data, RawListATA: nextProps.data, labels: nextProps.labels });
            this.props.dispatch(reportAction.method(datasets[0], labels[0]))
        }
    }

    render() {
        return (<div class="col-md-4 col-sm-4 col-xs-12">
            <Bar data={this.state.data} title='Count' getElementAtEvent={this.getElementAtEvent.bind(this)} />
        </div>
        )
    }
}

正如你在我的案例中所看到的,当我收到一个新的道具数据时,我重绘我的条形图(通过设置新的状态),然后发出新的动作

所以,对我来说,我必须做一次双重检查: 一旦在componentWillReceiveProps中设置新状态,并且shouldComponentUpdate停止不必要的更新。 但我认为这个解决方案并不好,所以你有什么建议可以提高代码性能吗

0 个答案:

没有答案
相关问题