reactjs - 在反应中获取后未设置数据
问题描述
这是我的组件代码,employ
它没有设置数据但得到正确的计数行(空)。
我想在从服务器端获取数据后设置数据。
import React, { Component } from 'react';
export class Employ extends React.Component {
constructor(props) {
super(props);
this.state = {
employ: []
};
}
componentDidMount() {
fetch("api/SampleData/GetEmpl")
.then(res => res.json())
.then(
(result) => {
this.setState({
employ: result
});
}
);
}
render() {
return (
<div>
<h2>Employ Data...</h2>
<table className="table stripted bordered hover">
<thead>
<tr>
<th>EmployeeID</th>
<th>FullName</th>
<th>EMPCode</th>
<th>Mobile</th>
<th>Position</th>
</tr>
</thead>
<tbody>
{this.state.employ.map(emp => (
<tr key={Math.random()}>
<td>{emp.EmployeeID}</td>
<td>{emp.FullName}</td>
<td>{emp.EMPCode}</td>
<td>{emp.Mobile}</td>
<td>{emp.Position}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
我使用 Asp.net.Api.core 连接数据库(后端)。
解决方案
您可以setState
用作回调函数。
import React, { Component } from 'react';
export class Employ extends Component {
constructor(props) {
super(props);
this.state = {
employ: []
};
}
componentDidMount() {
fetch("api/SampleData/GetEmpl")
.then(res => res.json())
.then(result => {
this.setState(() => ({
employ: result
}))
})
}
render() {
return (
<div>
... YOUR JSX CODE GOES HERE ...
</div>
)
}
}
推荐阅读
- java - 致命异常:java.lang.RuntimeException 无法获取应用程序信息
- java - 您可以将 Minecraft 版本的文件夹从 PC 复制并粘贴到 Mac 上吗?
- javascript - 分组条形图上的 D3js 标签
- swift - Swift UITableView numberOfRows 在节中添加或删除行时出错
- xpath - 如何与 sxpath 进行交集
- swift - 如何在 iOS 13 模态屏幕上快速添加导航栏标题
- javascript - Discord.js 复制另一个机器人的嵌入
- angular - 角度方法不保存变量的值
- amazon-web-services - 通过 Cloudwatch 实现用户日志记录自动化
- python - Having issues with my first python web scraper part 2 (The Sequel)