[嗨,我正在尝试从jsonplaceholder获取用户数据,并使用该数据更新我的状态。我获取数据并将其记录到控制台没有问题。但是当我尝试setState时,我仍然得到一个空对象。感谢您的帮助。谢谢。
这是我的代码:
class ProfilePage extends React.Component {
state = {
profileDetails: {},
};
componentDidMount() {
this.fetchDetails();
}
fetchDetails = async () => {
const baseUrl = "https://jsonplaceholder.typicode.com";
const pathname = this.props.history.location.pathname;
const response = await fetch(`${baseUrl}${pathname}`);
const data = await response.json();
console.log(data); // I can see the data i want here in the console.
this.setState = { profileDetails: data };
console.log(this.state.profileDetails); // I get an empty object here.
};
render() {
return <h1>Name: {this.state.profileDetails.name}</h1>;
}
}
export default ProfilePage;
提供检查数据的条件是否可用:-
if(data)
this.setState = ({ profileDetails: data });
请这样更改-this.setState({profileDetails:data});