找不到类组件函数

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


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


HUH函数
浏览 131回答 2
2回答

慕斯709654

response.json是一个函数。您正在将其分配给tasks国家。所以当你尝试使用Array.prototype.map(),tasks不是一个数组。调用它而不是将其分配给任务:&nbsp; &nbsp; async componentDidMount(){&nbsp; &nbsp; &nbsp; &nbsp; const response = await fetch('https://nztodo.herokuapp.com/api/task/?format=json');&nbsp; &nbsp; &nbsp; &nbsp; const tasks = await response.json() // Call json function here&nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tasks&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }

MMMHUHU

response.json 是一个函数,因此你不能映射一个函数。只需将此行更改为const&nbsp;tasks&nbsp;=&nbsp;await&nbsp;response.json();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript