首页 > 解决方案 > 在 ReactJS 中将数据映射到表

问题描述

我已成功从我的 API 中检索数据并将该数据设置为 setOfAllBooks 状态。我想将 setOfAllBooks 中的数据映射到组件中的 a 。页面加载标题正常,但我的数据不存在。我认为 mmy map() 函数应该有问题。

import React, { Component } from 'react';
import './ViewAll.css';
import axios from 'axios'
const rootURL = 'http://localhost:5000';

const TableRow = ({ row }) => (
    <tr class="table-light">
        <th scope="row" key={row.title}>{row.title}</th>
        <td key={row.author}>{row.author}</td>
        <td key={row.isbn}>{row.isbn}</td>
        <td key={row.isbn}>24</td>
    </tr>
)

const Table = ({data}) => (
    <table class="table table-hover">
        <thead>
            <tr class="table-primary">
                <th scope="col">Title</th>
                <th scope="col">Author</th>
                <th scope="col">ISBN</th>
                <th scope="col">No. Of Copies</th>
            </tr>
        </thead>
        <tbody>
            {data.map(row => {
                <TableRow row={row} />
            })}
        </tbody>
    </table>

)
class ViewAll extends Component {
    constructor(props){
        super(props);

        this.state = {
            setOfAllBooks: []
        }
    }

    componentDidMount(){
        axios.get(`${rootURL}/api/book/viewAll`)
            .then(res => {
                this.setState({ setOfAllBooks: res.data });
                console.log(this.state.setOfAllBooks)
            })
    }

    render(){
        return(          
            <div>
                <Table data={this.state.setOfAllBooks} />       
            </div>
        )
    }
}

export default ViewAll;

标签: reactjs

解决方案


return你在.map通话中错过了。

{data.map(row => {
  // Missing return here. Add return, otherwise
  // callback function of the map returns undefined
  // which is the default return value of each functions
  // in JS
  <TableRow row={row} />
 // return <TableRow row={row} /> will fix it.

})}

或者编写箭头函数的隐式返回版本。

{data.map(row => <TableRow row={row} />)}

推荐阅读