【发布时间】:2020-06-25 03:12:30
【问题描述】:
我正在尝试在 ReactJS 中获取以下 API 响应数据。我不知道该怎么做..有人可以帮我吗?在此先感谢您,我真的很感谢您提供的任何帮助或建议。
对于我的最终输出,我希望最终循环数组中的每个响应,并像 API 响应一样显示它们,除了在一个表中表示每个商店的地址和邮政详细信息。
API 响应
[
{
title: 'Paragon',
address: '290 Orchard Road #B1-03 Singapore 238859',
postal: '238859'
},
{
title: 'BreadTalk IHQ',
address: '30 Tai Seng Street #01-02 Singapore 534013',
postal: '534013'
},
{
title: 'City Square Mall',
address: '180 Kitchener Road #01-10 Singapore 208539',
postal: '208539'
}
]
代码(details.js)
class Crawler extends React.Component {
// Create constructor with props
constructor(props) {
super(props);
// Create a state that takes in the SEEDURL
this.state = {
seedURL: '',
response: null,
error: null
};
}
// The seed url taken from the input
const seedURL = this.state;
// Take the seedURL and send to API using axios
const url = "/api";
// Send data using axios
axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
try {
// Axios takes in the url and SeedURL
axios
.post(url, seedURL)
.then((res) => {
this.setState({response: res, error: null})
})
.catch((err) => {
this.setState({error: err, response: null})
});
} catch (e) {
console.log(e);
render() {
return(
// How do i read the response here?
);
}
}
【问题讨论】:
-
您是否尝试过安慰来自 api 的响应?我想你会进入 res.data 然后你可以 setState 它进入响应状态。