[英]Data not set after fetch in react
This is my code for component employ
which not set data but gets count rows correct ( empty ).这是我的组件
employ
代码,它没有设置数据但得到正确的计数行(空)。
I want to set the data after fetching from the server-side.我想在从服务器端获取数据后设置数据。
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>
);
}
}
I used Asp.net.Api.core for connecting database(backend).我使用 Asp.net.Api.core 连接数据库(后端)。
You can use setState
as callback function.您可以使用
setState
作为回调 function。
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>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.