我正在尝试使用reactjs渲染solr数据,在地图中我有它们。现在,其中有一个按钮。我想调用一个Web服务,如果我将ID传递给它,它会提供布尔结果。
Spring引导中的API返回
{
"isShortlisted": true
}
在react jsx文件中
isShortlistedUser = async(id)=>{
let response = await isShortlisted(id);
if(response.isShortlisted===true){
return 'Shortlisted';
}else{
return 'Shortlist';
}
}
在构造函数中,我有以下代码。
constructor(props) {
super(props);
this.state = {
users:[],
page:0,
rowsPerPage:5,
count:0
}
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.reloadUserList = this.reloadUserList.bind(this);
this.handleChangePage = this.handleChangePage.bind(this);
this.handleChangeRowsPerPage = this.handleChangeRowsPerPage.bind(this);
this.shortlistUser = this.shortlistUser.bind(this);
this.unshortlistUser = this.unshortlistUser.bind(this);
this.isShortlistedUser = this.isShortlistedUser.bind(this);
}
我使用下面的地图在render函数中进行渲染。...
{this.state.users.map(row => (
<div className="profile_top" key={row.id}><a href="#">
<h2>{row.id} | Profile Created by {row.profileCreatedBy}</h2>
...
<div className="buttons">
<div className="vertical">Send Mail</div>
<div className="vertical">
{this.isShortlistedUser(row.id)}
</div>
<div className="vertical">Send Interest</div>
</div>
</div>
<div className="clearfix"> </div>
</a></div>
))}
<TablePagination
rowsPerPageOptions={[5, 10, 25, 50]}
component="div"
count={this.state.count}
rowsPerPage={this.state.rowsPerPage}
page={this.state.page}
backIconButtonProps={{
'aria-label': 'previous page',
}}
nextIconButtonProps={{
'aria-label': 'next page',
}}
onChangePage={this.handleChangePage}
onChangeRowsPerPage={this.handleChangeRowsPerPage}
/>
但是它给了我下面的错误
{this.isShortlistedUser(row.id)}
错误:对象作为React子对象无效(找到:[object Promise])。如果要渲染子级集合,请改用数组。
我想做的是,如果它从Web服务提供了正确的文本,则该文本应为“入围/不入围”,否则为“入围”
您正在调用不带await
关键字的异步函数,因此它将返回Promise,而不是您期望的布尔值。但是,render()
不能是异步函数功能,这意味着无法在等待状态下调用isShortlistedUser
,并且您需要将此数据提取移至render()
之外。这样做不是一个好主意的另一个原因是,每次重新渲染时都将再次执行请求。附带说明一下,如果可能的话,最好找到一种方法来对请求进行分组。否则,每行将执行一个API请求。