首页 > 解决方案 > React + NodeJs Fetch 问题

问题描述

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

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

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

从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
            })
        }
    });
});

这是我的continents.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;

问题:

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

标签: javascriptnode.jsreactjs

解决方案


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}));
}

推荐阅读