![](/img/trans.png)
[英]reactjs ToDo List- Uncaught TypeError: Cannot read property 'map' of undefined
[英]Map undefined in ReactJS code for todo list app
我剛剛開始使用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?),我也將其發布!
謝謝!
可能是在調用render時未初始化待辦事項,或者您的Ajax調用未返回您期望的結果。
嘗試在渲染之前檢查待辦事項是否已定義
todos && todos.map...
還要檢查您的Ajax響應是否符合您的要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.