我使用 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 處理獲取呼叫并將它們代理到正確的服務器。但是現在我被困在如何在 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 模板中所做的那樣顯示我的資料。
任何幫助,將不勝感激!
uj5u.com熱心網友回復:
這很簡單,應該是這樣的:
<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 個映射函式。
uj5u.com熱心網友回復:
您可以使用與您在 HTML 模板上所做的非常相似的方式來執行此操作 .map
{myData.map((item) => (
<tr>
{item.map((d) => (
<td>{d}</td>
))}
</tr>
))}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397305.html
標籤:javascript Python 反应 烧瓶
