![](/img/trans.png)
[英]Uncaught TypeError: Cannot read property 'state' of undefined - React.js
[英]React.js: Uncaught TypeError: Cannot read property 'tasks' of undefined
第一次使用React.js。 使用React.js前端和Rails后端构建ToDo应用。 这是我的task.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'));
})
views / 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}/>
上Uncaught TypeError: Cannot read property 'tasks' of undefined
我不知道为什么。 另一方面,如果我删除data={this.props.tasks}
则this.props在所有函数中均未定义。 这与功能componentWillMount有关吗? 如果是这样,如何在渲染之前调用此函数?
所以我的问题是我渲染了两次:
$(document).ready(function () {
React.render(<Tasks data={this.props.tasks}/>, document.getElementById('tasks'));
});
我根本不需要这个。 似乎index.html.erb文件中的<%= react_component 'Tasks', { data: @tasks } %>
已调用render。 这是一个耗时的课程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.