javascript - React + NodeJs 获取问题

标签 javascript node.js reactjs

我正在尝试获取我的 api 的以下结果(运行良好) http://localhost:5000/api/continents

{"data":[{"continentId":3,"CName":"Atlantis"},{"continentId":2,"CName":"Devias"},{"continentId":1,"CName":"Lorencia"}]}

进入一个 react 组件(一个简单的数组开始)。

server.js中提取的端点代码:

app.get('/api/continents', (req, res) => {
    connection.query(SELECT_ALL_CONTINENTS_QUERY, (err, results) => {
        if(err){
            return res.send(err)
        }
        else{
            return res.json({
                data: results
            })
        }
    });
});

这是我的Continues.js代码:

import React, { Component } from 'react';
import './continents.css';

class Continents extends Component {
    constructor() {
        super();
        this.state = {
            continents: []
        }
    }

    ComponentDidMount() {
        fetch('http://localhost:5000/api/continents')
            .then(res => res.json())
            .then(continents => this.setState({continents}, () => console.log('Continents fetched..', continents)));
    }

  render() {
    return (
      <div>
        <h2>Continents</h2>
      </div>
    );
  }
}

export default Continents;

这是App.js代码:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Continents from './components/continents/continents';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Developed with NodeJS + React</h1>
        </header>
        <Continents />
      </div>
    );
  }
}

export default App;

问题:

大陆数组为空。未获取数据。但是,没有错误。如果有人能指导我朝正确的方向解决这个问题,我将非常感激。非常感谢。

最佳答案

ComponentDidMount是一个函数,所以它不应该大写,它应该是:componentDidMount .

并且您将错误的值传递给 setState方法,你应该通过 {continents: continents.data}而不是 continents对象本身。

更正后的代码:

componentDidMount() {
    fetch('http://localhost:5000/api/continents')
        .then(res => res.json())
        .then(continents => this.setState({continents: continents.data}));
}

关于javascript - React + NodeJs 获取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53271118/

相关文章:

javascript - 错误 [ERR_STREAM_WRITE_AFTER_END] : write after end [npm-request with socket. io]

javascript - 添加带有 url 的 anchor ,同时将 url 作为属性传递

javascript - ReactJS 的这段代码中的曲线括号有什么问题

javascript - 为什么弹出窗口出现在底部而不是居中?

node.js - 如何在(之前)PM2 启动时要求 dotenv/config 文件

javascript - 如何在jquery中分割ajax的Response html

javascript - 如何检查 Mongoose 中是否存在值

reactjs - 使用reactify使用ES6导入语法转换jsx

javascript - 如何使用 JQuery 检查输入单选按钮?

javascript - Angular Material 6 中用于自动完成的无限滚动