我无法将我的骨干集合传入反应组件

时间:2015-04-15 17:22:16

标签: javascript backbone.js reactjs

当我将其作为道具传递给反应组件时,我的主干集合集合不会填充。我尝试使用componentDidmount和componentWillMount首先获取集合,但仍然没有填充集合。如果我通过设置指向DecksIndex的窗口变量来测试代码,并在控制台工具中调用getInstance()然后获取 ,数据加载正常。我的代码如下:

 //router.js
var DeckComponent = require("./views/deck.jsx")
var DecksIndex = React.createFactory(require("./views/decks.jsx"))
var decksCollection = require("./component/collections/decks.js");

module.exports = Backbone.Router.extend({

    initialize: function(){
        this.rootEl = document.getElementById('container');
    },

    routes: {
        "":"index",
        "decks/:id":"deckShow"
    },

    index: function(){

        var decks = new DecksIndex({decks: decksCollection.getInstance()});
        this._swapView(decks)
        console.log("hooray!")
    },

    deckShow: function(id){
        //var deck = Flashcards.Collections.decks.getOrFetch(id);
        var showDeck = new DeckComponent();
        this._swapView(showDeck);
    },

    _swapView: function(view){
        if (this.currentView) {
            React.unmountComponentAtNode(this.rootEl);
        }
        this.currentView = view
        React.render(view, document.getElementById('container'));
    }   

});


//decks.js

var deck = require('../models/deck.js')
var decks = Backbone.Collection.extend({
  url: "/api/decks",
  model: deck,
  getOrFetch: function(id){
        var model = this.get(id);
        var that = this;
        if (model) {
            model.fetch();
        }else{
            model = new deck({id: id})
            model.fetch({
                success: function(){
                    that.add(model)
                }
            })
        }
        return model;
    },

    parse: function (data) {
        debugger;
        return data.objects
    },

});

decks.getInstance = _.memoize(function () {
  return new decks();
});

module.exports = decks;

//decks.jsx
var DecksList = React.createClass({

    render: function() {

            return (
              <div className="deck-list">
              {
                this.props.decks.map(function (deck) {
                    var title = deck.name
                    debugger;
                  return (
                    <div key={deck.id} className="note-summary">
                      {title}
                    </div>
                  );
                })
              }
              </div>
            );
      }
});

module.exports = DecksList;

1 个答案:

答案 0 :(得分:1)

这是管理状态的容器组件有意义的情况的示例。如果DecksList有一个容器在安装时检索该集合,并且只有在数据可用时才呈现DecksList,它可能会解决问题。这是一篇关于模式的好文章:https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0