我遇到了資料沒有從 React 中的 API 回應呈現的問題,即使我確實收到了它。
我有以下“管理員通知”組件:
import React from "react";
import './Admin-notifications.css';
import axios from 'axios';
class AdminNotifications extends React.Component {
constructor(){
super();
this.state = {
events:[
{
"id": 1,
"name": "Fotosinteza plantelor",
"start_date": 1637496120,
"end_date": 4098071460,
"location": "Cluj-Napoca",
"description": "Aduceti planta",
"status": "pending",
"id_organizer": 2,
"id_type": 1
},
{
"id": 2,
"name": "Cantecul greierilor de peste imas",
"start_date": 1637669280,
"end_date": 4098071460,
"location": "Imas",
"description": "In padurea cu alune aveau casa 2 pitici",
"status": "pending",
"id_organizer": 2,
"id_type": 1
},
{
"id": 4,
"name": "test",
"start_date": 1637518260,
"end_date": 4098071460,
"location": "test",
"description": "test",
"status": "pending",
"id_organizer": 2,
"id_type": 1
}
]
}
this.state2={
events:[],
}
}
getEvents(){
axios
.get("http://127.0.0.1:8000/api/getevents")
.then(response =>{
this.state2.events = response.data;
})
.catch(err => console.log(err));
};
render(){
this.getEvents();
console.log(this.state);
console.log(this.state2);
const {events} = this.state2;
return(
<main className="mw6 center main">
{
events.map((event)=>{
return(
<article key={event.id} className="dt w-100 hight padd bb pb2 component" href="#0">
<div className="col-md-3">
<div className="dtc w2 w3-ns v-mid">
{/* <img src={event.img}
alt="event image from organizator"
className="ba b--black-10 db br-100 w2 w3-ns h2 h3-ns"/> */}
</div>
<div className="dtc v-mid pl3">
<h1 className="f6 f5-ns fw6 lh-title black mv0">{event.name} </h1>
<h2 className="f6 fw4 mt0 mb0 black-60">{event.description}</h2>
</div>
<div className="dtc v-mid">
<form className="w-100 tr">
<button className="btn" type="submit">Accept</button>
</form>
</div>
<div className="dtc v-mid">
<form className="w-100 tr">
<button className="btn" type="submit">Decline</button>
</form>
</div>
</div>
</article>
)})
}
</main>
)
}
}
export default AdminNotifications;
在那里,您可以看到我有兩個狀態:state 和 state2。“this.state”是來自 API 的資料的硬編碼變體,“this.state2”是來自 API 的資料。
這是render() 中console.log() 的圖片,其中第一個'events' 屬于“state”,第二個屬于“state2”: 
如果我們使用“狀態”進行映射,則網站的外觀如下所示:
const {events} = this.state;
return(
<main className="mw6 center main">
{
events.map((event)=>{
...
圖片: 
這很好,這就是我希望網站的樣子。
以下是使用來自 API 的資料的樣子:
const {events} = this.state2;
return(
<main className="mw6 center main">
{
events.map((event)=>{
...
圖片: 
以下是 API 呼叫:

我還可以為您提供后端代碼。
API視圖:
@api_view(['GET'])
def getevents(request):
if request.method == "GET":
events = Event.objects.all()
serializer = EventSerializer(events, many=True)
return Response(serializer.data)
Yes, I did take care that there are no overwrites. This is the only view for this path.
Here is the Serializer that I have used:
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = '__all__'
Here is the model of the "Event":
class Event(models.Model):
name = models.TextField()
id_organizer = models.ForeignKey(User, on_delete=CASCADE, db_column='id_organizer')
start_date = models.BigIntegerField()
end_date = models.BigIntegerField()
location = models.TextField()
description = models.TextField()
id_type = models.ForeignKey(EventType, on_delete=CASCADE, db_column='id_type')
status = models.CharField(max_length = 50)
class Meta:
db_table="events"
Here is the table's database from where I get the data:

I did a print before returning the data in Django. Here is the result:
@api_view(['GET'])
def getevents(request):
if request.method == "GET":
events = Event.objects.all()
serializer = EventSerializer(events, many=True)
print(serializer.data)
return Response(serializer.data)
Picture

As you may have noticed, the API got called twice. I cannot really explain why this is happening, but in order to confirm this, if I add a console.log() inside the function that calls the API, and I get the console.log() twice, meaning that the function does calls twice.
getEvents(){
axios
.get("http://127.0.0.1:8000/api/getevents")
.then(response =>{
this.state2.events = response.data;
console.log("test1");
})
.catch(err => console.log(err));
};
Picture:

I have no idea why it is being called twice. But I do suspect it is one of the problems.
And here are the URL paths:
urlpatterns = [
path('api/login', views.login),
path('api/addevent', views.addevent),
path('api/getevents', views.getevents),
]
我嘗試使用 Promise 型別,以不同方式決議資料并將其推送到“state2”,將資料直接回傳到渲染中,但沒有任何效果。
uj5u.com熱心網友回復:
找到的解決方法:
constructor(){
super();
this.state = {
events:[]
}
}
componentDidMount(){
axios
.get("http://127.0.0.1:8000/api/getevents")
.then(response =>{
this.setState({events: response.data});
})
.catch(err => console.log(err));
}
老實說,我不知道為什么它不能以其他方式作業。但很高興解決了這個問題。
uj5u.com熱心網友回復:
您不能直接操作狀態,必須使用 this.setStae 函式來更新它,如下所示
getEvents(){
axios
.get("http://127.0.0.1:8000/api/getevents")
.then(response =>{
this.setState({events:response.data})
console.log("test1");
})
.catch(err => console.log(err));
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/373456.html
標籤:javascript 反应 姜戈 休息
