【发布时间】:2021-08-24 15:22:24
【问题描述】:
我正在尝试使用 Dango-REST-Framwork 将我的 React 前端连接到我的 Django 后端以创建 API。但我无法使用 React 获取我的数据。在我的尝试没有成功后,我尝试了 React 文档中的 this 示例。每次我尝试映射和“打印”我的结果时,都会显示此错误:
类型错误:项目未定义
这是我的代码:
import React, { Component } from 'react';
import axios from 'axios';
import {ThemeNavbar} from '../../../components';
import EinsatzTableRow from './components/EinsatzTableRow';
import './EinsaetzePage.scss';
export default class EinsatzePage extends Component {
state = {
error: null,
isLoaded: false,
items: []
};
componentDidMount() {
axios.get("http://127.0.0.1:8000/api/einsatzverwaltung/")
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div> <ThemeNavbar></ThemeNavbar><div>Loading...</div></div>;
} else{
return (
<div className="">
<ThemeNavbar></ThemeNavbar>
<div className="container">
<table class="table table-striped">
{items.map(item => (
<EinsatzTableRow einsatznummer="" alarmierungszeit="" stichwort="" meldebild="" ort="" einsatzbericht_link="#"></EinsatzTableRow>
))}
</tbody>
</table>
</div>
</div>
);
}
}
}
如果我检查 api 页面 (http://localhost:8000/api/einsatzverwaltung/) 一切正常:
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"id": 2,
"created": "2021-06-06T08:40:17.636978Z",
"updated": "2021-06-06T08:40:17.636978Z",
"status": 1,
"einsatz_start": "2021-01-21T21:33:00Z",
"einsatz_end": "2021-01-21T21:33:00Z",
"einsatzort": "Test",
"einsatzbericht": "ksnf jneog nroi nwoenf iownef inweof weio nwioe nfiowen ionweio cniweo cinwe iocwion c",
"images": null,
"meldebild": "Alarmo",
"author": null,
"stichwort": null,
"alarmierungsart": null,
"organisation": null,
"fahrzeuge_ext": null
},
{
"id": 1,
"created": "2021-06-06T08:40:11.084004Z",
"updated": "2021-06-06T08:40:11.084004Z",
"status": 1,
"einsatz_start": "2021-01-21T21:33:00Z",
"einsatz_end": "2021-01-21T21:33:00Z",
"einsatzort": "Test",
"einsatzbericht": "ksnf jneog nroi nwoenf iownef inweof weio nwioe nfiowen ionweio cniweo cinwe iocwion c",
"images": null,
"meldebild": "Alarmo",
"author": null,
"stichwort": null,
"alarmierungsart": null,
"organisation": null,
"fahrzeuge_ext": null
}
]
【问题讨论】:
-
我对反应不是很熟悉,但我认为数据不会在 result.items 上返回。
标签: javascript reactjs django django-rest-framework