小编典典

处理react.js中的骨干模型/集合更改

reactjs

在过去的几周里,我一直在与Facebook框架React.js和Backbone一起工作,但是我仍然不确定是否有什么最合适的方法来重新渲染React组件。已作为道具传递。

目前我要做的是在componenentWillMount集合上设置change/add/remove侦听器,并在触发时设置状态:

componentWillMount: function(){
    var myCollection = this.props.myCollection;
    var updateState = function(){
        this.setState({myCollection: myCollection.models});
    }

    myCollections.on("add remove", updateState, this);
    updateState();
}

render: function(){
    var listItems = this.state.myCollection.map(function(item){
        return <li>{item.get("someAttr")}</li>;
    });
    return <ul>{listItems}</ul>;
}

我已经看到了将模型克隆到状态的示例:

var updateState = function () {
    this.setState({ myCollection: _.clone(this.myCollection.models) });
};

我也看到了变体,其中props中的模型/集合直接在渲染中使用,而不是使用状态,然后在集合/模型发生更改时调用forceUpdate,从而导致组件重新渲染

componentWillMount: function(){
    var myCollection = this.props.myCollection;
    myCollections.on("add remove", this.forceUpdate, this);
}

render: function(){
    var listItems = this.props.myCollection.map(function(item){
        return <li>{item.get("someAttr")}</li>;
    });
    return <ul>{listItems}</ul>;
}

不同方法有什么优点和缺点?有没有办法做到这就是 React的方式


阅读 232

收藏
2020-07-22

共1个答案

小编典典

您可以使用基于此BackboneMixin的mixin来自动绑定和取消绑定监听器,而不是手动绑定事件监听器:

https://github.com/facebook/react/blob/1be9a9e/examples/todomvc-
backbone/js/app.js#L148-L171

然后你只要写

var List = React.createClass({
    mixins: [BackboneMixin],

    getBackboneModels: function() {
        return [this.props.myCollection];
    },

    render: function(){
        var listItems = this.props.myCollection.map(function(item){
            return <li>{item.get("someAttr")}</li>;
        });
        return <ul>{listItems}</ul>;
    }
});

集合中的任何更改都会重新渲染该组件。您只需要将BackboneMixin放在顶层组件上,所有后代都会在同一时间自动重新呈现。

2020-07-22