首页 > 解决方案 > 从 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;

标签: djangoreactjsdjango-rest-framework

解决方案


您正在映射整个表。这会将每个项目映射到一行:

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>
    );
  }
}

推荐阅读