我正在尝试从API提取数据,然后将其设置在我的州并在表格中显示该州。问题是首先调用render方法,并导致我的状态未定义,从而导致此问题:
console.log()
https://i.gyazo.com/642f8d6fe3481d2db9763091618e19de.png
state = {
loading: true,
data: [],
customColumns: [],
}
componentDidMount = () => {
axios.get('http://localhost:8080/lagbevakning/revision/subscriptions?id=' + (this.props.match.params.id)).then(response => {
this.setState({
data: response.data,
loading: false
})
})
axios.get('http://localhost:8080/lagbevakning/company?id=' + sessionStorage.getItem("id")).then(response2 => {
this.setState({
customColumns: response2.data
})
})
}
displayCustomColumn = (columnInput) => {
if(columnInput === null) {
return
} else {
return <Table.HeaderCell>{columnInput}</Table.HeaderCell>
}
}
displayList = () => {
return (
<div>
<Table celled>
<Table.Header>
<Table.Row>
{this.displayCustomColumn(this.state.customColumns.customHeaderName1)}
{this.displayCustomColumn(this.state.customColumns.customHeaderName2)}
</Table.Row>
</Table.Header>
{this.state.data.map((item, i) => (
<Table.Body key={i}>
<Table.Row>
<Table.Cell>{item}</Table.Cell>
<Table.Cell>{item}</Table.Cell>
</Table.Row>
</Table.Body>
))}
</Table>
</div>
)}
render() {
return (
<div>
{this.state.loading
? <div><h1>LOADING...</h1></div>
:
<h2> Company Name: {this.state.customColumns.companyName} <br/>
Revision Name: {this.state.data.name} <br/>
Revision ID: {this.state.data.id} </h2>
}
{this.displayList()}
</div>
)
}
}
非常感谢您提出有关解决此问题的建议。
答案 0 :(得分:0)
render() {
return (
<div>
{this.state.loading
? <div><h1>LOADING...</h1></div>
:
<h2> Company Name: {this.state.customColumns.companyName} <br/>
Revision Name: {this.state.data.name} <br/>
Revision ID: {this.state.data.id} </h2>
}
{this.displayList()}
</div>
)
}
我认为您期望数据为数组,因此您无法从数据状态访问名称和ID。检查响应的结构并进行相应设置。
答案 1 :(得分:0)
您可以尝试添加以下内容吗?
render() {
return (
<div>
{this.state.loading
? <div><h1>LOADING...</h1></div>
:
<h2> Company Name: {this.state.customColumns.companyName} <br/>
Revision Name: {this.state.data.name} <br/>
Revision ID: {this.state.data.id} </h2>
}
{this.state.data.length > 0 && this.displayList()}
</div>
)
}
答案 2 :(得分:0)
您可以尝试一下。
render() {
if (this.state.loading) return <div><h1>LOADING...</h1></div>;
return (
<div>
{this.state.data && this.state.data.length &&
<div>
<h2> Company Name: {this.state.customColumns.companyName} <br />
Revision Name: {this.state.data.name} <br />
Revision ID: {this.state.data.id} </h2>
}
{this.displayList()}
</div>
</div>
)
}
}
如果loading
为真,则可以立即返回。
在此之下,您可以检查data
是对象数组。