【发布时间】:2019-03-07 23:20:16
【问题描述】:
我正在使用 react 和 express 创建我的第一个 crud 应用程序,但我无法创建从 sql cosulta 接收的动态表。
错误是:props.datos.map 不是函数。
我不知道我做的是否正确,或者我使用了不好的做法。
我看到了,可能是因为调用是异步的,因此。
我必须更改组件的状态,而不是为 props 传递数据。
表达js:
const express = require('express');
const app = express();
var mysql = require('mysql');
const port = process.env.PORT || 5000;
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'shells'
});
connection.connect();
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
// create a GET route
app.get('/express', (req, res) => {
// res.send({ saludo: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
connection.query('select * from shell', function(err, rows, fields) {
res.send(JSON.stringify(rows));
});
});
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import SideBar from './sideBar'
import Table from './table'
class App extends Component {
render() {
return (
<SideBar>
<Table datos={rows}/>
</SideBar>
);
}
}
export default App;
var rows= fetch('/express')
.then(function(response) {
console.log(response)
return response;
})
.then(function(myJson) {
console.log(myJson);
});
console.debug(rows)
console.log(rows)
Table.js
function SimpleTable(props) {
return (
<Paper className={props.root}>
<Table className={props.table}>
<TableHead>
<TableRow>
<TableCell>Familia</TableCell>
<TableCell numeric>Genero</TableCell>
<TableCell numeric>Especie </TableCell>
<TableCell numeric>Calidad </TableCell>
<TableCell numeric>Tamaño </TableCell>
<TableCell numeric>Pais </TableCell>
<TableCell numeric>Comentario </TableCell>
<TableCell numeric>Precio </TableCell>
</TableRow>
</TableHead>
<TableBody>
{props.datos.map(molusco => {
return (
<TableRow >
<TableCell component="th" scope="row">
{molusco.familia}
</TableCell>
<TableCell numeric>{molusco.genero}</TableCell>
<TableCell numeric>{molusco.especie}</TableCell>
<TableCell numeric>{molusco.calidad}</TableCell>
<TableCell numeric>{molusco.tamaño}</TableCell>
<TableCell numeric>{molusco.pais}</TableCell>
<TableCell numeric>{molusco.comentario}</TableCell>
<TableCell numeric>{molusco.precio}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Paper>
);
}
SimpleTable.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(SimpleTable);
【问题讨论】:
-
您是否在
Table.js中导入import React from 'react'? -
是的,我做到了。这不是问题。谢谢你的回答
-
如果
props.datos.map不是一个函数,最可能的情况是您在rows变量中提供给Table的内容不是一个数组(因此它没有原型中的 map 函数)。尝试记录rows以查看您是否真的在传递数组。 -
我创建了一个 console.log 来打印 rows 变量,但它没有打印任何内容,我不知道我会做错什么或者 row 是否没有任何内容。我通过以下方式完成了 console.log ({rows})。我觉得你说的是对的。 rows 不是数组,因为它是空的(我认为)
标签: javascript node.js reactjs express