簡體   English   中英

class 組件 function 未找到

[英]class components function not found

我有一個問題,這是一個 class 組件:

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是 function。 您將其分配給tasks state。 因此,當您嘗試使用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
        });
    }

response.json 是 function,因此您不能 map 超過 ZC1C425268E68385D1AB5074F14C1 只需將此行更改為

const tasks = await response.json();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM