查询数据库后如何在React中显示数据?



我是React新手。我一直在使用模板引擎,很长一段时间。我甚至会说太长了。我只是想试一试。

让我们看看问题:在我以前工作过的许多应用程序中,我一直在使用这种模式-从数据库中获取一些东西,然后渲染页面,使获取的数据本地到视图。例如:

//express powered backend
app.get('/', (req, res) => {
//do something with the database and then:
res.render('some_template_view', {
fetched_data,
});
})

你如何在反应中做到这一点?我可以在组件安装时获取一些东西,但我想可能还有其他方法?

可以使用express作为数据库的api,在客户端使用fetch或xhr。

看这个例子:

// index.js - express app
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors());
app.get('/database', (req, res) => {
// Process data from your database
res.json(/*Info to be sent*/{name: 'Peter'});
});
app.listen(8080, () => console.log('Server is running'));
// index.js - React app example
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: ''
}
}
componentDidMount() {
// Example fetch
return fetch('http://localhost:8080/database')
.then(res => res.json())
.then(data => { return this.setState({name: data.name})})
.catch(console.log);
}
render() {
return (
<div>
<h1>Data received: </h1>
<p>{this.state.name}</p>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById(/*Root element id*/'root')
);

最新更新