首页 > 解决方案 > 如何使用 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 天并尝试了所有方法,但没有任何效果:(

标签: reactjs

解决方案


如果你这样做

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>
        ))}
    )
 }

推荐阅读