【问题标题】:How to display data from Flask in React App?如何在 React App 中显示来自 Flask 的数据?
【发布时间】:2022-01-25 15:52:18
【问题描述】:

我使用 Flask 作为后端从 MySQL 数据库中检索数据,如下所示:

@app.route('/create', methods=['GET'])
def get_family():
    cursor.execute("SELECT * FROM individual")
    data = cursor.fetchall() 
    return render_template('index.html', data=data)

最后一行将必要的数据发送到位于模板文件夹中的 HTML 文件,并成功在表格中显示我的数据:

<table>
  <tr>
     <td>First Name</td>
     <td>Last Name</td>
     <td>Gender</td>
  </tr>
  {% for item in data %}
  <tr>
    {% for d in item %}
     <td>{{d}}</td>
     {% endfor%}
  </tr>
  {% endfor %}
 </table>

但是,我不想在 html 模板中而是在我的 React 应用程序中显示这些数据。我的 React 文件有一个完全独立的文件夹。

我为我的 Flask API 添加了一个代理以避免 CORS 问题,并允许 React 处理 fetch 调用并将它们代理到正确的服务器。但是现在我被困在如何在 React 中准确地显示我的数据。这是我最初的尝试:

function Test() {
  const [myData, setMyData] = useState([{}])
  useEffect(() => {
    fetch('/create').then(
      response => response.json()
    ).then(data => setMyData(data.myData))
  }, []);
  return (
    <div>
      <table>
        <tr>
           <td>First Name</td>
           <td>Last Name</td>
           <td>Gender</td>
        </tr>
        mapping here?
        <tr>
          mapping here?
           <td>{{myData}}</td>
        </tr>
       </table>
    </div>
  );
}

我不确定我应该如何映射才能像在那个 HTML 模板中那样显示我的数据。

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript python reactjs flask


    【解决方案1】:

    您可以使用与在 HTML 模板上使用 .map 非常相似的方式来完成此操作

    {myData.map((item) => (
      <tr>
        {item.map((d) => (
          <td>{d}</td>
        ))}
      </tr>
    ))}
    

    【讨论】:

    • 谢谢!成功了!
    【解决方案2】:

    这很简单,应该是这样的:

    <table>
      <thead>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Gender</th>
        </tr>
      </thead>
      <tbody>
        myData.map((item, idx) => (
        <tr key={idx}>
          <td>{item.firstName}</td>
          <td>{item.lastName}</td>
          <td>{item.genre}</td>
        </tr>
      </tbody>
    </table>
    

    或者您也可以映射 td 并拥有 2 个映射函数。

    【讨论】:

    • 谢谢!成功了!
    猜你喜欢
    • 1970-01-01
    • 2019-02-28
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2017-09-20
    • 2017-03-07
    相关资源
    最近更新 更多