React表未从网络请求加载



我正试图从我的api创建一个表。我做了以下代码:

export class News extends Component {
constructor(props) {
super(props);
this.state = {
dataObject: [],
currentPage: 1,
ItemsPerPage: 10,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id),
});
}
getAll = () => {
return new newsServices().GetNews().then((data) => {
this.setState({ dataObject: data });
});
};
componentDidMount() {
this.getAll();
}
render() {
return (
<div>
<h1>Get the Latest BEE News</h1>
<table>
<tbody>
{this.state.dataObject.map((result) => {
return (
<tr>
<td>{result.Subject}</td>
<td>{result.Summary}</td>
<td>{result.Url}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
}

但我得到以下错误:Uncaught TypeError: this.state.dataObject.map is not a function我的Json回应如下:

[{"Id":"00000000-0000-0000-0000-000000000000",
"Date":"2019-05-06T00:00:00",
"Subject":"Barloworld optimistic ‘black public’ will take up offer to invest in new property group",
"Summary":"Industrial group Barloworld is optimistic that qualifying black South Africans will respond positively to its offer to buy a maximum of 30% of the shares available in a new black-owned property company, called Khula Sizwe Property Holdings, being created as part of a larger R3.5-billion broad-based black economic empowerment (BBBEE) transaction.",
"Url":"https://m.engineeringnews.co.za/article/barloworld-optimistic-black-public-will-take-up-offer-to-invest-in-new-property-group-2019-04-25",
"Active":true}

我只需要得到我的表来显示数据、主题、摘要和Url,如果我能得到一个来显示,那么我应该能够得到所有它们的显示,但我不知道为什么我的代码不工作

UPDATE这是我的getNews函数:

export class newsServices extends BaseApiService {
GetNews() {
return this.get(ApiUrls.NewsGetAll);
}
//ApiUrls is 'News/GetAll'

我的基本ApiService:

const axios = require('axios');
import { baseApiUrl } from '../constants/ApiUrls';
export class BaseApiService {
get<T>(url: string) {
return axios.get(`${baseApiUrl}${url}`).then((response: any) => {
return {
isSuccess: true,
value: response.data as T,
errorMessage: ''
}
}).catch((ex: any) => {
return {
isSuccess: false,
value: {} as T,
errorMessage: ex.message
}
});
}
post<T>(url: string, data: any) {
return axios.post(`${baseApiUrl}${url}`, data).then((response: any) => {
return {
isSuccess: true,
value: response.data as T,
errorMessage: ''
}
}).catch((ex: any) => {
return {
isSuccess: false,
value: {} as T,
errorMessage: ex.message
}
});
}
}
}

baseApiServiceget方法返回一个对象,而不是数组。

get<T>(url: string) {
return axios.get(`${baseApiUrl}${url}`).then((response: any) => {
return {
isSuccess: true,
value: response.data as T,
errorMessage: ''
}
}).catch((ex: any) => {
return {
isSuccess: false,
value: {} as T,
errorMessage: ex.message
}
});
}

因此,在您的代码中,当您将GetNews的响应分配给您所在州的dataObject属性时,您会得到这样的结果。。。

this.state.dataObject = {
isSuccess: true,
value: [your data]
errorMessage: ''
}

您不能对其调用map,因为它不是数组。

要解决此问题,请从GetNews返回分配给value的数据数组,或在访问状态时引用this.state.dataObject.value,或将值属性分配给dataObjectthis.setState({ dataObject: data.value })

最新更新