我有一个问题,这是一个类组件:import React from 'react'; import ListToDo from './ListToDo';export default class TestClass extends React.Component{ state ={ tasks:[] } async componentDidMount(){ const response = await fetch('https://nztodo.herokuapp.com/api/task/?format=json'); const tasks = await response.json this.setState({ tasks }); } render(){ return( <ul className="list-group"> { this.state.tasks.map(function(singleTask){ return <ListToDo task={singleTask} key={singleTask.id} /> }) } </ul> ); }错误是: TypeError: this.state.tasks.map is not a function } 为什么?我需要安装一些吗?
2 回答

慕斯709654
TA贡献1840条经验 获得超5个赞
response.json是一个函数。您正在将其分配给tasks国家。所以当你尝试使用Array.prototype.map(),tasks不是一个数组。
调用它而不是将其分配给任务:
async componentDidMount(){
const response = await fetch('https://nztodo.herokuapp.com/api/task/?format=json');
const tasks = await response.json() // Call json function here
this.setState({
tasks
});
}

MMMHUHU
TA贡献1834条经验 获得超8个赞
response.json 是一个函数,因此你不能映射一个函数。只需将此行更改为
const tasks = await response.json();
添加回答
举报
0/150
提交
取消