无法从 React 前端获取 express API

我现在已经进入第三周尝试简单地从 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


有人可以解释一下获取这种格式的数据的正确方法吗?


慕哥6287543
浏览 147回答 3
3回答

芜湖不芜

你需要在构造函数中初始化 todosconstructor(){&nbsp; &nbsp; &nbsp; &nbsp;super();&nbsp; &nbsp; &nbsp; &nbsp;this.state ={key: 0, title: '', todos: []};&nbsp; &nbsp;}因为最初在调用 render 方法时,API 仍在进行中,当时todos是未定义的。因此,当您尝试.map在未定义的情况下运行 a 时,它会崩溃。

米琪卡哇伊

我认为你混合了 state 和 todos 数组。在构造函数中初始化状态如下:constructor(){&nbsp; &nbsp;super();&nbsp; &nbsp;this.state ={ todos: [key: 0, title: '']};}在渲染函数中:render() {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h1>todos</h1>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {this.state.todos.map(todo =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div key = {todo.key} > title: {todo.title} </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }

小唯快跑啊

您todos将在初始运行render前未定义componentDidMount,因此您必须todos像这样使用空数组初始化constructor(){&nbsp; &nbsp; &nbsp; &nbsp;super();&nbsp; &nbsp; &nbsp; &nbsp;this.state ={key: 0, title: '', todos: []};&nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript