reactjs - 在 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;
解决方案
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} />)}
推荐阅读
- excel - 在这种情况下如何获得总利润?
- c# - 任务激活 HighVersionLie 失败
- excel - 如何将每个条形图顶部的 % 更改为数字?
- flutter - 使用 Material () 或 Scaffold () 小部件时,使用不透明度设置颜色样式不起作用
- flutter - 在 Java 中加密和在 dart Flutter 中解密
- flutter - 如何在颤动的列表视图中对多个表单实现表单验证?
- python - 从几年的时间序列中删除一天中的某些小时v - python
- cordova - 科尔多瓦插件是否与电容器(离子)一起使用
- mysql - Windows 更新后 Xammp MySQL 无法启动
- google-bigquery - 根据另一个表中的开始日期和结束日期对值求和