django - 从 Django Rest Api 获取并显示数据
问题描述
在遵循了许多关于如何在 React 中集成 Django rest 的教程之后,我成功地从我的 api 中获取数据,但是我的表头重复了我从数据中获取的对象的数量,我的数据中有 3 个产品所以也就是做表 3 次。当我尝试移动 {this.state.todos.map(item => ( 就在我收到错误之前,因为那个“破坏”了我的标签,所以我可以把 {this.state.todos.map(item => (就在我之前或之后,有人可以帮助我吗?我只想对每个项目重复一遍,但不是所有表,谢谢你的帮助
import React, { Component } from 'react';
class Products extends Component {
state = {
todos: []
};
async componentDidMount() {
try {
const res = await fetch('http://127.0.0.1:8000/api/');
const todos = await res.json();
this.setState({
todos
});
} catch (e) {
console.log(e);
}
}
render() {
return (
<div>
{this.state.todos.map(item => (
<table class="table table-bordered table-hover table-striped">
<thead>
<tr class="bg-gray text-white">
<th>Id</th>
<th>Category</th>
<th>Name</th>
<th>Short Description</th>
<th>Price</th>
<th class="text-center">Image</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">{item.title}</td>,
<td scope="row"></td>,
<td></td>
<td></td>
<td></td>
<td></td>
<td>Delete</td>
</tr>
</tbody>
</table>
))}
</div>
);
}
}
export default Products;
解决方案
您正在映射整个表。这会将每个项目映射到一行:
class Products extends Component {
state = {
todos: []
};
async componentDidMount() {
try {
const res = await fetch('http://127.0.0.1:8000/api/');
const todos = await res.json();
this.setState({
todos
});
} catch (e) {
console.log(e);
}
}
render() {
return (
<div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr class="bg-gray text-white">
<th>Id</th>
<th>Category</th>
<th>Name</th>
<th>Short Description</th>
<th>Price</th>
<th class="text-center">Image</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{this.state.todos.map(item => (
<tr>
<td scope="row">{item.title}</td>,
<td scope="row"></td>,
<td></td>
<td></td>
<td></td>
<td></td>
<td>Delete</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
推荐阅读
- perl - 从模板工具包中的代码引用调用
- tensorflow - How to connect RNN at the end of a CNN to use to train video frames?
- r - 如何在ggplot2中制作单个堆叠条形图
- java - 如何为输入地址制作好的editText?
- macos - 尽管做了 chmod 777,但权限被拒绝
- python - 使用 Python 从 Data.gov.sg API (json) 下载实时降雨数据
- python - 如果键值的值是单独列表的成员,则无法有效地从字典中提取键
- css - CSS 溢出自动及其工作
- django - 序列化 Django 模型时如何包含父对象?
- visual-studio-code - Ctrl+Shift+E 将特殊字符插入文件而不是在 VS Code 中显示资源管理器窗格