React.js:Uncaught TypeError:无法读取属性' tasks'未定义的

时间:2015-07-18 01:46:14

标签: javascript reactjs

第一次使用React.js。使用React.js前端和Rails后端构建ToDo应用程序。这是我的tasks.js.jsx文件:

"use strict";

var List = React.createClass({
    renderItems: function() {
        return _.map(this.props.tasks, function(task) {
            return <li className="list-group-item pointer" >{task.name}</li>;
        });
    },

    render: function() {
      return  <ul className="list-group">
                {this.renderItems()}
              </ul>;
    }
});

var Tasks = React.createClass({

  getInitialState: function(){
    return {
      tasks: this.props.data
    }
  },

  getDefaultProps: function(){
    return {
      tasks: []
    }
  },

  renderList: function(complete){
    return <List tasks={_.filter(this.state.tasks, function(x) { return x.complete === complete; })} />;
  },

  render: function() {
    return  <div className="todos">
              <div className="incomplete-todo">
                <h1>Todo List</h1>
                <h2 className="spacing-bottom">Incomplete</h2>
                {this.renderList(false)}
              </div>
              <div className="complete-todo">
                <h2 className="spacing-bottom">Complete</h2>
                {this.renderList(true)}
              </div>
            </div>
  }
});

$(document).ready(function () {
  React.render(<Tasks data={this.props.tasks}/>, document.getElementById('tasks'));
})

视图/任务/ index.html.erb

<div id="tasks">
  <%= react_component 'Tasks', { data: @tasks } %>
</div>

控制器/ tasks_controller.rb

class TasksController < ApplicationController
  def index
    @tasks = Task.all
  end
end

虽然此代码呈现了从Rails传入的任务列表。我在Uncaught TypeError: Cannot read property 'tasks' of undefined上获得了<Tasks data={this.props.tasks}/>,但我不知道为什么。另一方面,如果我删除data={this.props.tasks},那么this.props在我的所有函数中都是未定义的。这是否与函数componentWillMount有关?如果是这样,我如何在渲染之前调用此函数?

1 个答案:

答案 0 :(得分:0)

所以我的问题是我渲染了两次:

module.exports = {
    //This is the entry point for the webpack
    entry: {
    app: ['./public/index.jsx']
    },
    output: {
    // This is the name of the bundle which is created  when webpack runs
    path: './public',
    filename: 'bundle.js' 
    },
    module: {
        loaders: [
            {
                //tell webpack to use jsx-loader for all *.jsx files
                test: /\.jsx$/,
                loader: 'jsx-loader?insertPragma=React.DOM&harmony'
            }
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    }
}

我根本不需要这个。似乎index.html.erb文件中的$(document).ready(function () { React.render(<Tasks data={this.props.tasks}/>, document.getElementById('tasks')); }); 已经调用了render。这是一个耗时的课程。