【发布时间】:2018-07-14 00:52:29
【问题描述】:
我有一个通过 Express 连接到后端的 React 应用程序,我在其中查询 SQL 数据库以检索数据。最终目标是通过 React 显示该数据。
问题
我无法通过 SQL 查询返回的元素列表map。我太初学者了,不知道为什么,但我猜这是因为 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;
【问题讨论】:
-
您在代码中明确指出
allwatches只是一个空字符串。也许这是一个错误或需要正确填充?您也可能无法等待该异步调用运行,因此componentDidMount可能需要返回一个承诺,或等待结果。 -
@tadman 我不明白。我最初将 allwatches 设置为空,但随后 componentDidMount 应该更新其状态并将数据插入其中。
标签: javascript mysql node.js reactjs express