reactjs - 如何使用 react 迭代 API 调用的结果?
问题描述
我创建了一个搜索表单。用户可以搜索公司名称、名字和姓氏。我将搜索参数提交给 API:
https://hiddenlink.cfc?method=getSearch&companyname=${this.state.companyName}&firstname=${this.state.firstName}&lastname=${this.state.lastName}`)
我可以看到正在返回数据:
这是我的onSubmit
功能:
handleSubmit = async event => {
event.preventDefault();
const response = await axios.get(`linkhidden.cfc?method=getSearch&companyname=${this.state.companyName}&firstname=${this.state.firstName}&lastname=${this.state.lastName}`)
.then(result => {
this.setState({ phonebook: result.phonebook });
console.log(result);
});
};
如何使用 API 返回的数据更新状态并显示结果?
我已经用谷歌搜索了 3 天并尝试了所有方法,但没有任何效果:(
解决方案
如果你这样做
handleSubmit = event => {
event.preventDefault();
const response = axios .get( linkhidden.cfc?method=getSearch&companyname=${this.state.companyName}&firstname=${this.state.firstName}&lastname=${this.state.lastName} )
.then(result => {
this.setState({ phonebook: result.data.phonebook }); // replaces the current this.state.phonebook
console.log(result) // displays the result in the screenshot
});
};
}
然后你可以this.state.phonebook
在你的渲染中显示(注意,因为在你的截图phonebook
中是一个数组,我假设有多个条目)
render() {
return(
{ this.state.phonebook.map((item, index) => (
<ul key={'phonebook_'+index}>
{ // iterate through each property (or otherwise access them specifically with item.city, item.email_address, etc)
Object.keys(item).map((itemProperty, itemIndex) => (
<li key={'phonebook_'+index+'_'+itemIndex}>
{item[itemProperty]}
</li>
))
}
</ul>
))}
)
}
推荐阅读
- ruby-on-rails - 使用 Ajax 发布时如何检查我的数据库中是否已存在记录?
- android - ViewModel 中的 ObservableField 值不会使用数据绑定更新 UI
- html - 对齐嵌套的 div 并缩放而不移动
- sas - SAS:以特定方式显示数据
- haskell - 分解类型作为折叠中的种子
- jsdoc - jsdoc - 为多个功能重用文档?
- android - 如何知道 AsyncTask 是否在后台工作?
- angular - Angular 5 输入变化
- android - Google Assistant,将已安装的应用程序与没有 OAuth2 的助手连接
- ios - 逐字符动画 CATextLayer