3 回答

TA貢獻1796條經驗 獲得超7個贊
你需要在構造函數中初始化 todos
constructor(){
super();
this.state ={key: 0, title: '', todos: []};
}
因為最初在調用 render 方法時,API 仍在進行中,當時todos是未定義的。
因此,當您嘗試.map在未定義的情況下運行 a 時,它會崩潰。

TA貢獻1998條經驗 獲得超6個贊
我認為你混合了 state 和 todos 數組。在構造函數中初始化狀態如下:
constructor(){
super();
this.state ={ todos: [key: 0, title: '']};
}
在渲染函數中:
render() {
return (
<div className="App">
<h1>todos</h1>
{this.state.todos.map(todo =>
<div key = {todo.key} > title: {todo.title} </div>
)}
</div>
);
}

TA貢獻1863條經驗 獲得超2個贊
您todos將在初始運行render前未定義componentDidMount,因此您必須todos像這樣使用空數組初始化
constructor(){
super();
this.state ={key: 0, title: '', todos: []};
}
添加回答
舉報