javascript - 找不到类组件函数
问题描述
我有一个问题,这是一个类组件:
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 } 为什么?我需要安装一些吗?
解决方案
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
});
}
推荐阅读
- xcode - '...' 不是 Travis CI 上的后缀一元运算符
- jsp - 表单中的错误 404 通信 servlet/JSP
- prolog - 为什么不打印整个列表?
- javascript - 从包含重复项的数组中获取唯一的 ObjectID
- python - 如何从列表中将键和值添加到字典
- ios - 输入文本时 UIButton 自动换行不起作用?
- sql-server - 存储过程临时表跨越不同的用户和生命周期
- sql-server - SQL Server:如何在 WHERE 子句中使用 IF ELSE 或其他内容
- android - 从 SQLite DB 获取数据不返回字符串
- java - 无法找到对自己的关系的 Maven 依赖项