【发布时间】:2021-06-01 09:50:53
【问题描述】:
我的反应代码如下:
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { Link, NavLink } from 'react-router-dom';
interface AllEmployeeDataState {
empList: EmployeeData[];
loading: boolean;
}
export class AllEmployee extends React.Component<RouteComponentProps<{}>, AllEmployeeDataState> {
constructor() {
super();
this.state = { empList: [], loading: true };
fetch('api/Employee/Index')
.then(response => response.json())
.then(data => {
this.setState({ loading: false });
this.state.empList.push(data);
console.log(this.state.empList);
});
this.handleEdit = this.handleEdit.bind(this);
}
public render() {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: this.renderEmployeeTable(this.state.empList);
return <div>
<h1>Employee Data</h1>
<p>
<Link to="/Employee/Detail">Create New</Link>
</p>
{contents}
</div>;
}
private handleEdit(id: number) {
this.props.history.push("/Employee/Detail/" + id);
}
private renderEmployeeTable(empList: EmployeeData[]) {
return <table className='table'>
<thead>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Gender</th>
<th>Designation</th>
<th>City</th>
</tr>
</thead>
<tbody>
{empList.map((emp, i) => (
<tr key={i}>
<td>{emp.FldId}</td>
<td>{emp.FldName}</td>
<td>{emp.FldGender}</td>
<td>{emp.FldDesignation}</td>
<td>{emp.FldCity}</td>
</tr>
))}
</tbody>
</table>;
}
}
export class EmployeeData {
FldId: number = 0;
FldName: string = "";
FldFatherName: string = "";
FldGender: number = 0;
FldReligion: number = 0;
FldCnic: string = "";
FldDob: Date = new Date;
FldCity: number = 0;
FldPermanentAddress: string = "";
FldContactNumber: string = "";
FldNationality: number = 0;
FldEmailId: string = "";
FldStatus: boolean = false;
FldDateOfJoining: Date = new Date;
FldCreatedAt: Date = new Date;
FldCreatedBy: number = 0;
FldUpdatedAt: Date = new Date;
FldUpdatedBy: number = 0;
FldDesignation: number = 0;
FldUsername: string = "";
FldPassword: string = "";
}
但是当我运行代码时,它显示的是空白表。 现在我检查了浏览器控制台中的数据,“emp”和“emp.FldID”都显示了正确的数据。那为什么它没有显示在表格中? 当我将鼠标悬停在浏览器源选项卡中的 emp 上时,它显示完整的数据,但源选项卡中的单个 emp.FldId 未定义。
此外,如果我给出在构造函数中定义的硬编码数据,它在表格中显示得很好。
【问题讨论】:
-
您的代码中加载状态为“假”的部分在哪里???我找不到它。如果没有,请尝试在构造函数中添加它...谢谢
-
获取api数据时加载状态会设置为false。
标签: javascript json reactjs