繁体   English   中英

我在将主干集合传递到React组件时遇到麻烦

[英]I am having trouble passing in my backbone collection in to a react component

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

 //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;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM