reactjs - 在 reactjs 前端看不到来自 django 的数据
问题描述
我是新来的反应。我正在构建 django + react web-application 项目的完整代码https://github.com/mascai/django_examples/tree/master/02_django_react
当我提出请求时,http://127.0.0.1:8001/api/lead/
我会看到来自 Django 的有效数据。但是当我去的时候http://127.0.0.1:8001
我没有看到没有看到任何数据。
我认为前端的问题。
index.js
import React, { Component } from 'react';
import { render } from "react-dom";
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
loaded: false,
placeholder: "Loading"
};
}
componentDidMount() {
fetch("api/lead")
.then(response => {
if (response.status > 400) {
return this.setState(() => {
return { placeholder: "Something went wrong!" };
});
}
return response.json();
})
.then(data => {
this.setState(() => {
return {
data,
loaded: true
};
});
});
}
render() {
return (
<ul>
{this.state.data.map(contact => {
return (
<li key={contact.id}>
{contact.name} - {contact.email}
</li>
);
})}
</ul>
);
}
}
export default App;
const container = document.getElementById("app");
render(<App />, container);
index.html(看起来不错)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django REST with React
</head>
<body>
<div id="app">
<!-- React will load here -->
</div>
</body>
{% load static %}
<script src="{% static "frontend/main.js" %}"></script>
</html>
解决方案
您忘记了标题中的结束标签index.html
:
<title>Django REST with React</title>
并且脚本引号应该是这样的(注意双引号和单引号):
<script src="{% static 'frontend/main.js' %}"></script>
另一个问题是,当你构建你的 React 应用程序时,它会被放置在static/frontend/main.js/main.js
. 因此,您不仅要创建一个名为 的文件main.js
,还要创建一个名为main.js
.
为了解决这个问题,首先删除static/frontend
文件夹的内容(删除main.js
目录)。
然后转到package.json
并将脚本中的输出路径更改为
"scripts": {
"dev": "webpack --mode development ./src/index.js --output-path ./static/frontend",
"build": "webpack --mode production ./src/index.js --output-path ./static/frontend"
},
我还建议将<h1>
带有随机文本的标签放入您的组件中,以便您可以查看您的组件是否实际呈现。
最后使用这两个命令之一编译您的反应应用程序。
推荐阅读
- sql - 替换 select 语句中的特殊字符
- android - 具有静态浮动操作按钮的相对布局内的网格布局上的滚动视图
- visual-studio - Unity GUI 元素 - 我如何选择 whos 在顶部?
- node.js - 即使状态为 200 的响应准确,也会触发 catch 块
- java - 从 Docker 容器的 maven Quarkus 项目的资源文件夹中读取 txt 文件
- vim - 如何在 Vim 中列出 autocmd 组?
- angular - 如何解决 Ionic Angular 应用程序中的 CORS 策略问题?
- vba - 确定夏令时是否对 VBA 中的特定时区有效
- java - 在 oracle SQL 中正确排序分页结果
- netsuite - 将供应商付款应用于 NetSuite 中的费用报告