使用React状态来管理已实例化对象的列表?

时间:2016-10-03 19:48:20

标签: javascript reactjs backbone.js

我想检查每个集合我的实例,看看是否已经存在同一类型的另一个实例,这样我就可以使用存储的版本而不是创建一个新版本,如何使用react状态来保持列表以检查?

示例代码:

export default React.createBackboneClass({

    getInitialState() {
        return {
            data: [],
            groups: {}
        }
    },

    componentWillMount() {
        this.setState({
            data: this.props.collection
        });
    },

    render() {
        const gridGroups = this.state.data.map((model) => {

            let gridGroupsCollection = null;

            if(this.state.groups[model.get('id')]) {
                gridGroupsCollection = this.state.groups[model.get('id')];
            } else {
                gridGroupsCollection = this.state.groups[model.get('id')] = new GridGroupCollection([], {
                    groupId: model.get('id')
                });

                this.setState((previous) => {
                    groups: _.extend({}, previous, gridGroupsCollection)
                });
            }

            return <GridGroupComponent
                key={model.get('id')}
                name={model.get('n')}
                collection={gridGroupsCollection} />
        });

        return (
            <div>
                {gridGroups}
            </div>
        );
    }
});

1 个答案:

答案 0 :(得分:0)

几点。首先,我会使用componentWillReviewProps来完成繁重的工作。在渲染方法上执行此操作可能会更加昂贵。我还没有在状态对象上保存实例。是否需要缓存性能或解决排序问题?

此外,如前所述,从render方法调用setState将生成无限循环。当状态改变时调用render。

在旁注中我会考虑Redux,这提供了几种从数据操作中分离组件的整体方法。

<强>更新

This TodoMVC example可能会指出如何结合反应和骨干的方向:

 componentDidMount: function () {
        // Whenever there may be a change in the Backbone data, trigger a
        // reconcile.
        this.getBackboneCollections().forEach(function (collection) {
            // explicitly bind `null` to `forceUpdate`, as it demands a callback and
            // React validates that it's a function. `collection` events passes
            // additional arguments that are not functions
            collection.on('add remove change', this.forceUpdate.bind(this, null));
        }, this);
    },

    componentWillUnmount: function () {
        // Ensure that we clean up any dangling references when the component is
        // destroyed.
        this.getBackboneCollections().forEach(function (collection) {
            collection.off(null, null, this);
        }, this);
    }