我刚刚开始在ReactJS中编码,并且必须构建一个todo应用程序。现在显示从API调用接收的待办事项时出现问题。这是我得到的错误:
未捕获的TypeError:无法读取未定义的属性“map”
这是代码:
TodoList.js
import React from 'react';
import $ from 'jquery';
import TodoItem from './TodoItem';
class TodoList extends React.Component {
constructor() {
super();
this.state = {
todos: [
{id: 0, title: "", completed: false}
]
};
}
componentDidMount() {
this.loadTodos();
}
loadTodos(event) {
let component = this;
$.getJSON(`https://whispering-thicket-55256.herokuapp.com/todos.json`, function(data) {
console.log(data);
component.setState({
todos: data.todos
});
});
}
renderTodos(todo, i) {
return (
<TodoItem
key={todo.id}
id={todo.id}
title={todo.title}
completed={todo.completed}
createdAt={todo.created_at}
updatedAt={todo.updated_at} />
);
}
render() {
let todos = this.state.todos
return (
<div>
<ul>
{todos.map(this.renderTodos.bind(this))}
</ul>
</div>
);
}
}
export default TodoList;
TodoItem.js
import React from 'react';
import jQuery from 'jquery';
class TodoItem extends React.Component {
componentDidMount() {
this.setState({
id: this.props.id,
title: this.props.title,
completed: this.props.completed,
createdAt: this.props.createdAt,
updatedAt: this.props.updatedAt
})
}
render() {
console.log(this.props);
return (
<li>{this.props.title}</li>
);
}
}
export default TodoItem;
我看不出我在这里做错了什么..希望有人可以帮助我。我想要实现的是在列表中显示.json url中的所有待办事项。 如果您需要更多代码(app.js?),那么我也会发布这个代码!
谢谢!
答案 0 :(得分:0)
调用render时可能没有初始化todos,或者你的Ajax调用没有返回你期望的内容。
尝试在渲染之前检查是否已定义待办事项
todos && todos.map...
同时检查您的Ajax响应是否是您需要的。