javascript - 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;
问题:
大陆数组为空。未提取数据。但是,没有错误。如果有人能引导我朝着正确的方向解决这个问题,我将不胜感激。非常感谢。
解决方案
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}));
}
推荐阅读
- ruby-on-rails - 在您的应用程序中检测到安全漏洞
- gimp - 移除双 Alpha 通道
- javascript - 成功的ajax调用后删除点击范围
- javascript - 单击从 ajax 调用的结果中选择(无 jquery)
- javascript - 在 JavaScript 中将 Promise 的结果合并到一个数组中
- javascript - Cannot save object in localStorage
- godot - 为什么我的 path2d 位置没有更新?
- bash - 将 ${} 占位符解析为 shell 脚本中的绝对路径
- javascript - 当我有可重用的反应组件、父组件或子组件(可重用组件)时,在 React 中的何处获取数据
- r - 热图:如何仅对行进行聚类并保持热图列标签的顺序与 df 中的相同?