Reactjs TypeError:this.state.employees.map不是函数
这里,我使用状态中的employee作为对象 在尝试将其呈现为表时,获取Reactjs TypeError:this.state.employees.map不是函数,reactjs,Reactjs,这里,我使用状态中的employee作为对象 在尝试将其呈现为表时,获取映射的此错误不是一个函数。后端api正在返回员工列表 class Employee extends React.Component{ constructor(props){ super(props); this.state={ employees:[] }; } componentDidMount(){
映射的此错误不是一个函数。后端api正在返回员工列表
class Employee extends React.Component{
constructor(props){
super(props);
this.state={
employees:[]
};
}
componentDidMount(){
fetch("http://localhost:8080/employee/getEmployees").then(res=>res.json).then(
result=>{
console.log(result.id)
this.setState({employees:result});
}
)
}
render(){
return (<div>
<h2>welcome to employee.</h2>
<table>
<thead>
<tr>
<th>Employee id</th>
<th>Employee name</th>
<th>Employee age</th>
<th>Employee companyid</th>
<th>Employee stream</th>
</tr>
</thead>
<tbody>
{this.state.employees.map(emp=>(
<tr key={emp.id}>
<td>{emp.id}</td>
<td>{emp.name}</td>
<td>{emp.age}</td>
<td>{emp.companyId}</td>
<td>{emp.stream}</td>
</tr>
))}
</tbody>
</table>
</div>)
}
}
ReactDOM.render(<Employee />, document.getElementById("root"))
类Employee扩展React.Component{
建造师(道具){
超级(道具);
这个州={
员工:[]
};
}
componentDidMount(){
取回(“http://localhost:8080/employee/getEmployees)。然后(res=>res.json)。然后(
结果=>{
console.log(result.id)
this.setState({employees:result});
}
)
}
render(){
返回(
欢迎来到这里。
员工id
员工姓名
员工年龄
雇员公司ID
员工流
{this.state.employees.map(emp=>(
{emp.id}
{emp.name}
{emp.age}
{emp.companyId}
{emp.stream}
))}
)
}
}
ReactDOM.render(,document.getElementById(“根”))
您正在将一个函数传递给第二个,然后
不会将结果解析为JSON
只需将res=>res.json
更改为res=>res.json()
1.在加载员工之前,已调用渲染函数。
2.您没有在json对象中转换该响应
3.尝试使用mobx库中的toJS转换为json。
4.然后尝试{this.state.employees&&this.state.employees.map(…)}Thefetch
API执行异步任务并返回承诺。因此,在最初渲染组件时,不会设置数据。要克服此错误,可以在从服务器获取数据并设置状态时有条件地呈现加载的文本
另外,fetch
返回一个JSON
承诺。我们可以使用像这样的res=>res.JSON()
方法来读取和解析JSON
if(this.state.employees.length==0){
返回“加载…”;
}
render(){
返回(
欢迎来到这里。
/*代码的其余部分*/
}
或者,如果你能简单地把它呈现成这样
{
这是州政府雇员&&
this.state.employees.map((emp)=>(
{emp.id}
{emp.name}
{emp.age}
{emp.companyId}
{emp.stream}
));
}
```{this.state.employees&&this.state.employees.length&&this.state.employees.map(emp=>(``始终添加防御代码。您是否从console.log(result)获得结果,它是一个数组?NB res=>res.json()不是res=>res.json()