亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

無法從 React 前端獲取 express API

無法從 React 前端獲取 express API

慕哥6287543 2022-05-26 16:50:04
我現在已經進入第三周嘗試簡單地從 Express API 獲取 json 響應到 React 應用程序中。我已經嘗試了至少 40 個小時的教程,但我仍然無法讓它工作。出于絕望,我想把它貼在這里,我知道我會被處以私刑,因為這將是某種形式的重復,但我正在尋找一個人來解決這個問題,希望能幫助我理解我做錯了什么。這是我從 React 調用它的最新嘗試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;這會產生一個錯誤:Uncaught TypeError: Cannot read property 'map' of undefined有人可以解釋一下獲取這種格式的數據的正確方法嗎?
查看完整描述

3 回答

?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

你需要在構造函數中初始化 todos


constructor(){

       super();

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

   }


因為最初在調用 render 方法時,API 仍在進行中,當時todos是未定義的。


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


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

TA貢獻1998條經驗 獲得超6個贊

我認為你混合了 state 和 todos 數組。在構造函數中初始化狀態如下:


constructor(){

   super();

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

}

在渲染函數中:


render() {

        return (

            <div className="App">

                <h1>todos</h1>

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

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

              )}

            </div>

        );

    }


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

TA貢獻1863條經驗 獲得超2個贊

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


constructor(){

       super();

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

   }


查看完整回答
反對 回復 2022-05-26
  • 3 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號