3 回答
TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊
你需要在構(gòu)造函數(shù)中初始化 todos
constructor(){
super();
this.state ={key: 0, title: '', todos: []};
}
因?yàn)樽畛踉谡{(diào)用 render 方法時(shí),API 仍在進(jìn)行中,當(dāng)時(shí)todos是未定義的。
因此,當(dāng)您嘗試.map在未定義的情況下運(yùn)行 a 時(shí),它會(huì)崩潰。
TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
我認(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)驗(yàn) 獲得超2個(gè)贊
您todos將在初始運(yùn)行render前未定義componentDidMount,因此您必須todos像這樣使用空數(shù)組初始化
constructor(){
super();
this.state ={key: 0, title: '', todos: []};
}
添加回答
舉報(bào)
