【问题标题】:Beginner Node/React/MySQL -> querying the db and displaying the result初学者节点/React/MySQL -> 查询数据库并显示结果
【发布时间】: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


【解决方案1】:

解决了。

我不得不在 server.js 中替换 res.json(rows); 而不是 res.send(JSON.stringify(rows));,并且在我的组件中我必须在我的状态中添加一个空数组,所以我从 allwatches : '' 转到 allwatches : [] `

【讨论】:

  • 在将事物初始化为这样的无意义值时应该小心。许多 JavaScript 代码是异步的,这意味着操作的顺序并不总是很明显。尽可能让事情保持未初始化,而不是用空字符串之类的虚拟值填充。我认为这个“修复”使代码在你的空数组上运行而不会出错,直到它被正确填充,但这可能不是你的意图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
  • 2015-01-28
  • 1970-01-01
相关资源
最近更新 更多