【问题标题】:How to display data in React after querying the database?查询数据库后如何在 React 中显示数据?
【发布时间】:2021-02-04 17:15:01
【问题描述】:

我是 React 新手。很长一段时间以来,我一直在使用模板引擎。我什至会说太长。我只是在反应中弄湿了我的脚。

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

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

你是怎么做的?我可以在组件安装时获取一些东西,但我认为可能还有其他方法?

【问题讨论】:

  • 在组件挂载时获取实际上是非常标准的反应。在获取数据时提供一些有效的初始状态并有条件地呈现一些“正在加载”的 UI。如果可以,请附上Minimal, Complete, and Reproducible Code Example。

标签: javascript node.js reactjs


【解决方案1】:

好的,为此您可以使用 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')
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多