3 回答

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

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

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