我在我的react js Web应用程序中集成了数据表。
它可以处理代码页列表中提到的示例数据
我试图使其成为组件,但没有得到结果。我是新的 反应迟钝,无法暗示进一步的进展。
这是我的导入软件包的列表
import axios from 'axios'
import React, {Component} from 'react'
import {BrowserRouter,Route,Switch,Link} from 'react-router-dom'
import { MDBDataTable} from 'mdbreact';
//以下调用获取我在控制台日志中确认的数据
axios.get('/api/pagelist').then(response => {
var pagelist = JSON.stringify(response.data);
console.log(pagelist);
});
//与示例兼容的测试数据
var pagelist = [{
name: 'Tiger Nixon',
position: 'System Architect',
office: 'Edinburgh',
age: '61',
date: '2011/04/25',
salary: '$12320'
},
{
name: 'Gavin Joyce',
position: 'Developer',
office: 'Edinburgh',
age: '42',
date: '2010/12/22',
salary: '$92'
},
{
name: 'Jennifer Chang',
position: 'Regional Director',
office: 'Singapore',
age: '28',
date: '2010/11/14',
salary: '$357'
},
{
name: 'Donna Snider',
position: 'Customer Support',
office: 'New York',
age: '27',
date: '2011/01/25',
salary: '$112'
}
];
//只需按照文档的指导复制功能并更改列
const DatatablePage = () => {
const data = {
columns: [{
label: 'ID',
field: 'id',
sort: 'asc',
width: 60
},
{
label: 'Name',
field: 'name',
sort: 'asc',
width: 150
},
{
label: 'Title',
field: 'title',
sort: 'asc',
width: 150
},
{
label: 'Slug',
field: 'slug',
sort: 'asc',
width: 100
},
{
label: 'Content',
field: 'content',
sort: 'asc',
width: 250
},
{
label: 'Created',
field: 'created_at',
sort: 'asc',
width: 100
}
],
rows: pagelist
};
return (
<MDBDataTable striped bordered hover data = {data}/>
);
}
//最后将其导出
export default DatatablePage;
答案 0 :(得分:0)
对我来说似乎是一个范围界定问题。您用于存储页面数据的data变量的作用域是axios回调。代码离开该回调后,您的数据将不再可访问。
axios.get('/api/pagelist').then(response => {
// pageList scoped locally. not accessible outside. this is why the
// console.log works, but there's no data in the table.
var pagelist = JSON.stringify(response.data);
console.log(pagelist);
});
假设您正在使用组件,建议您添加一个构造函数并创建一个state属性。例如
constructor(props) {
super(props);
this.state = {pageList: []} ;
}
您需要在axios.get中对此进行更新。...
axios.get('/api/pagelist').then(response => {
// The below line may not be exactly correct. May need to review.
this.setState({pagelist: JSON.stringify(response.data)}, console.log("state updated));
});
最后,datatables方法中的行分配必须为
rows: this.state.pagelist