这段代码不断给我带来无法读取未定义属性映射的错误,我只是想从数据库中获取一些数据
import React, { Component } from 'react';
import './App.css';
class App extends Component {
state={
products:[]
}
componentDidMount(){
this.getProducts();
}
getProducts = _ =>{
fetch('http://localhost:8000/products')
.then(response => response.json())
.then(response => this.setState({products: response.data}))
.catch(err=>console.error(err))
}
renderProduct=({product_id,name})=> <div key={product_id}>{name}</div>
render() {
const{products}=this.state;
return (
<div className="App">
{products.map(this.renderProduct)}
</div>
);
}
}
export default App;
服务器端发送代码
app.get('/products', function (req, res) {
connection.query('SELECT * FROM prod', function (error, results, fields) {
if (error) throw error;
res.send(results);
});
});
答案 0 :(得分:0)
主要问题在getProducts中,您需要确保response.data.products存在,它可能具有另一个名称。检查console.log(data)
。
getProducts = _ =>{
fetch('http://localhost:8000/products')
.then(response => response.json())
.then(data => this.setState({products: data.products }) || console.log(data))
// data is an object you need to pick the correct key
.catch(err=>console.error(err))
}
您应该检查阵列中是否有可用产品。
render() {
const{products}=this.state;
return (
<div className="App">
{products.length ? products.map(this.renderProduct) : 'No products available'}
</div>
);
}
答案 1 :(得分:0)
您的数据库中的CRUD是否有可能返回Null,未定义的值,或者服务器发送的是对象而不是数组,这会导致您的状态在componetDidMount中被非数组数据更新,因此有问题吗?