第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法從 React 前端獲取 express API

無法從 React 前端獲取 express API

慕哥6287543 2022-05-26 16:50:04
我現(xiàn)在已經(jīng)進(jìn)入第三周嘗試簡單地從 Express API 獲取 json 響應(yīng)到 React 應(yīng)用程序中。我已經(jīng)嘗試了至少 40 個小時的教程,但我仍然無法讓它工作。出于絕望,我想把它貼在這里,我知道我會被處以私刑,因為這將是某種形式的重復(fù),但我正在尋找一個人來解決這個問題,希望能幫助我理解我做錯了什么。這是我從 React 調(diào)用它的最新嘗試import React, { Component } from 'react';class App extends Component {   constructor(){       super();       this.state ={key: 0, title: ''};   }   componentDidMount() {          fetch('http://localhost:3001/')            .then(res => {                console.log(res);                return res.json()             })            .then(todos => {                 console.log(todos);                 this.setState({ todos })             });         }   render() {        return (            <div className="App">                <h1>todos</h1>                {this.state.todos.map(todo =>                <div key = {this.state.key} > title: {this.state.title} </div>              )}            </div>        );    }}export default App;這會產(chǎn)生一個錯誤:Uncaught TypeError: Cannot read property 'map' of undefined有人可以解釋一下獲取這種格式的數(shù)據(jù)的正確方法嗎?
查看完整描述

3 回答

?
蕪湖不蕪

TA貢獻(xiàn)1796條經(jīng)驗 獲得超7個贊

你需要在構(gòu)造函數(shù)中初始化 todos


constructor(){

       super();

       this.state ={key: 0, title: '', todos: []};

   }


因為最初在調(diào)用 render 方法時,API 仍在進(jìn)行中,當(dāng)時todos是未定義的。


因此,當(dāng)您嘗試.map在未定義的情況下運行 a 時,它會崩潰。


查看完整回答
反對 回復(fù) 2022-05-26
?
米琪卡哇伊

TA貢獻(xiàn)1998條經(jīng)驗 獲得超6個贊

我認(rèn)為你混合了 state 和 todos 數(shù)組。在構(gòu)造函數(shù)中初始化狀態(tài)如下:


constructor(){

   super();

   this.state ={ todos: [key: 0, title: '']};

}

在渲染函數(shù)中:


render() {

        return (

            <div className="App">

                <h1>todos</h1>

                {this.state.todos.map(todo =>

                <div key = {todo.key} > title: {todo.title} </div>

              )}

            </div>

        );

    }


查看完整回答
反對 回復(fù) 2022-05-26
?
小唯快跑啊

TA貢獻(xiàn)1863條經(jīng)驗 獲得超2個贊

您todos將在初始運行render前未定義componentDidMount,因此您必須todos像這樣使用空數(shù)組初始化


constructor(){

       super();

       this.state ={key: 0, title: '', todos: []};

   }


查看完整回答
反對 回復(fù) 2022-05-26
  • 3 回答
  • 0 關(guān)注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號