我有一个通过Express连接到后端的React应用程序,在那里我查询SQL数据库以检索数据。最终目标是通过React显示该数据。
问题
我不能map
通过SQL查询返回的元素列表。我太初衷了,为什么,但我的猜测是因为SQL查询返回的数据是object
,我需要array
来映射它。因此会返回错误:TypeError: this.state.allwatches.filter is not a function
。
Server.js (似乎正在运作)
const express = require('express');
const app = express();
const port = 5000;
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : 'password',
database : 'Watches'
});
app.get('/getWatchesList', (req, res) => {
connection.connect();
connection.query('SELECT * from WatchesList', function(err, rows, fields) {
if (!err) {
res.send(JSON.stringify(rows));
} else {
console.log('Error while performing Query.');
}
});
connection.end();
});
app.listen(port, () => console.log(`Server started on port ${port}`));
WatchesList.js (似乎会导致问题)
import React, { Component } from 'react';
// Components
import Watche from './WatchesList_Components/Watche.js'
class WatchesList extends Component {
constructor() {
super();
this.state =
{
allwatches : ''
};
}
componentDidMount() {
fetch('/getWatchesList')
.then(res => res.json())
.then(allwatches_ => this.setState({allwatches: allwatches_}, () => console.log("successfully fetched allwatches", allwatches_)))
}
render() {
let filteredWatches = this.state.allwatches.filter((watche) => {
return watche.name.indexOf(this.props.filterText) > -1;
});
return (
<div>
{
filteredWatches.map(
(product) => {
return <Watche name={product.name} price={product.price} image={product.image} />
})
}
</div>
);
}
}
export default WatchesList;
答案 0 :(得分:0)
解决。
我必须在server.js res.json(rows);
而不是res.send(JSON.stringify(rows));
中替换,并且在我的组件中我必须在我的状态中添加一个空数组,所以我从allwatches : ''
转到{ {1}}
`