按照教程尝试学习反应。我很难从我的API(使用whatwg-fetch的mongodb中获取数据)并渲染项目。数据库正在运行,并且没有错误反应。开发人员工具报告“道具对象为空”,进行了一些研究并缩小了范围显然,它是在数据输入之前渲染的。但是,我实现了一个承诺,但结果没有改变。任何帮助将不胜感激。
我增加了一个诺言。
// App.js file
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import Product from "../components/product/product"
import HttpService from "../services/http-service";
const http = new HttpService();
class App extends Component {
constructor(props) {
super(props);
this.state = {
products: []
}
// Bind functions
this.loadData = this.loadData.bind(this);
this.productList = this.productList.bind(this);
this.loadData()
};
loadData = () => {
let self = this;
http.getProducts().then(data => {
self.setState({products: data})
}, err => {
});
}
productList = () => {
const list = this.state.products.map((product) =>
<div className="inItems" key={product._id}>
<Product title={product.title} price={product.price} imgUrl=
{product.imgUrl} />
</div>
);
console.log(list)
return (list)
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Welcome
</p>
<div className="container App-main">
<div className="items">
<h1>List Of Products</h1>
{this.productList()}
</div>
</div>
</header>
</div>
);
}
}
export default App;
// service.js文件
import "whatwg-fetch";
class HttpService {
getProducts = () => {
let promise = new Promise((resolve, reject) => {
fetch("http://localhost:7500/product-list", {mode: "no-cors",
credentials: 'include' })
.then(res => {
resolve(res.json())
}).catch(err => {
if (err) throw err;
reject(err)
})
});
return promise;
}
}
export default HttpService;
期望在屏幕上显示的项目。什么都没有显示,并且控制台中没有错误。
答案 0 :(得分:0)
您需要等待数据(const data = await http.getProducts())或仅使用axios https://www.npmjs.com/package/axios
。这意味着一旦收到响应,您将要做一些事情,但外部作用域仍将继续运行,并且数据仍为空