为什么这个React代码不可达,当它是一个数组,但工作于一个单一的对象



嗨,我想使用map函数来迭代我的数据,并在React中填充一个表。使用状态我设置我的变量为一个空数组,但当我来映射它的代码是不可达的,我不知道为什么。

注意:如果我在构造函数中映射一个单独的对象,它可以完美地工作。

更新

解决!_对不起,伙计们-我的错误-我错过了第二个render() {,这显然导致代码变得不可达

Eriks解决方案工作,但Get请求仍然没有发射-我理解这是一个单独的问题…

我们如何清理这篇文章?我是新来的?

这是因为你给数组赋了"Subbies"并映射条目"子条目";相同的名称,只是给map item一个不同的名称,比如"Subby"或者别的什么。并且这些值应该是map item的值,像这样:

const Subbies = this.state.subbieData;
const SubbieTable = Subbies.map(subby=> {
return
<tr>
<td>{subby.id}</td>
<td>{subby.contractor_name}</td>
<td>{subby.contractor_type}</td>
<td>{subby.contractor_email}o</td>
<td>{subby.contractor_phone_number}</td>
</tr>
})

这是因为map函数中的return和渲染没有返回任何东西。

import { Container, Table } from "react-bootstrap"
import RestClient from "../../common/RestClient"
import AppUrl from "../../common/AppUrl"
export class ViewAllSubbies extends Component {
constructor() {
super()
this.state = {
subbieData: []
}
}
componentDidMount() {
RestClient.GetRequest(AppUrl.AllSubbies).then(result => {
this.setState({ subbieData: result })
})
}
render() {
const Subbies = this.state.subbieData;
return (Subbies.map(item=> {
return (<tr>
<td>{item.id}</td>
<td>{item.contractor_name}</td>
<td>{item.contractor_type}</td>
<td>{item.contractor_email}o</td>
<td>{item.contractor_phone_number}</td>
</tr>)
}))
} 

请参考更新后的代码。