从 axios 获取的 json 对象显示名称属性时出现问题



https://codesandbox.io/s/currying-voice-toq9t - 我正在尝试将 json 对象保存到组件状态,然后将名称呈现到浏览器中。

getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com....."
)
.then(response => {
this.setState({
profile: {
name: response.data.name
}
});
})
.catch(error => this.setState({ error, isLoading: false }));
}

你的响应数据是一个数组形式,所以,你需要给Index,希望它能帮助你。

getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com/YRrbtT9qhg0/NISgcRm5hpqtvPF8I0tLkQ/result.json"
)
.then(response => {
this.setState({
profile: {
name: response.data[0].name
}
});
})
.catch(error => this.setState({ error, isLoading: false }));
}

response.data 是一个数组,其中第一个位置有您要查找的信息,因此 setState 应该是这样的:

this.setState({
profile: {
name: response.data[0].name
}
});

const [obj] = response.data;
this.setState({
profile: {
name: obj.name
}
});

您的response.data返回一个 array.so 您需要在循环中遍历它。

import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
export class Profile extends React.Component {
constructor(props) {
super(props);
this.state = { profile: [] };
}
componentDidMount() {
this.getProfile();
}
getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com/YRrbtT9qhg0/NISgcRm5hpqtvPF8I0tLkQ/result.json"
)
.then(response => {
console.log("response: ", response)
this.setState({
profile: response.data
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
let { name } = this.state.profile;
const { error } = this.state;
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Profile</h1>
{error ? <p>{error.message}</p> : null}
</header>
<div className="App-feeds" />
<div className="panel-list">
{this.state.profile.map((element) => <p>First Name: {element.name}</p>)}
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Profile />, rootElement);

相关内容

  • 没有找到相关文章

最新更新