gpt4 book ai didi

javascript - React.js - 从 API 正确加载单个帖子数据

转载 作者:行者123 更新时间:2023-11-29 19:02:19 24 4
gpt4 key购买 nike

我是 React 的新手,正在努力研究如何正确地从我的 API 为单个帖子加载数据。

我读到过我应该使用“componentDidMount”向 API 发出 GET 请求,但请求在组件呈现时尚未完成。所以我下面的代码不起作用,因为我收到错误:“无法读取未定义的属性 setState”。

我在这里做错了什么?我应该从其他地方调用 setState 吗?我的简单组件如下 - 谢谢。

import React from 'react';
import Header from './Header';
import axios from 'axios';

class SingleListing extends React.Component {

constructor(props) {
super(props);

this.state = {
listingData: {}
}
}

componentDidMount() {

// Get ID from URL
var URLsegments = this.props.location.pathname.slice(1).split('/');

// Load the listing data
axios.get('/api/listing/' + URLsegments[1])
.then(function(res){

let listingDataObject = res.data;
console.log(listingDataObject);
this.setState({
listingData: listingDataObject
});

})
.catch(function(err){
console.log(err);
});

}


render() {

console.log('helsdfdsfsdflssosso');
console.log(this.state.listingData);

return (
<div className="SingleListing">
<Header />
<div className="container">

<div>Property Address: {this.state.listingData.propertyAddress}</div>
This is a single listing
</div>
</div>
)
}

}
export default SingleListing;

最佳答案

您只需要根据数据是否已加载来更改您呈现的内容。

此外,在处理 axios 响应时应使用箭头函数,否则 this 设置不正确。

class SingleListing extends React.Component {
constructor(props) {
super(props);

this.state = {
listingData: null,
};
}

componentDidMount() {
// Get ID from URL
const URLsegments = this.props.location.pathname.slice(1).split('/');

// Load the listing data
axios
.get(`/api/listing/${URLsegments[1]}`)
.then(res => {
const listingDataObject = res.data;
console.log(listingDataObject);
this.setState({
listingData: listingDataObject,
});
})
.catch(err => {
console.log(err);
});
}

render() {
const isDataLoaded = this.state.listingData;

if (!isDataLoaded) {
return <div>Loading...</div>;
}

return (
<div className="SingleListing">
<Header />
<div className="container">
<div>Property Address: {this.state.listingData.propertyAddress}</div>
This is a single listing
</div>
</div>
);
}
}

export default SingleListing;

关于javascript - React.js - 从 API 正确加载单个帖子数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45950783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com