首页 > 解决方案 > 找不到类组件函数

问题描述

我有一个问题,这是一个类组件:

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 } 为什么?我需要安装一些吗?

标签: javascriptnode.jsreactjs

解决方案


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
        });
    }

推荐阅读