當我使用 fetch 帶來筆記串列和 consol.log 時,它什么也沒顯示。網址沒有錯,我已經仔細檢查過了。這是代碼:
import React, { useState, useEffect } from 'react'
const NotesListPage = () => {
let [notes, setNotes] = useState([])
useEffect(() => {
}, [])
let getNotes = async () => {
let response = await fetch('http://127.0.0.1:8000/api/notes/')
let data = await response.json()
console.log(data)
setNotes(data)
}
return (
<div>
</div>
)
}
export default NotesListPage
這是api部分:
@api_view(['GET'])
def getNotes(request):
notes = Note.objects.all()
serializer = NoteSerializer(notes, many=True)
return Response(serializer.data)
uj5u.com熱心網友回復:
import React, { useState, useEffect } from 'react'
const NotesListPage = () => {
let [notes, setNotes] = useState([])
useEffect(() => {
getNotes();
}, [])
let getNotes = async () => {
let response = await fetch('http://127.0.0.1:8000/api/notes/')
let data = await response.json()
console.log(data)
setNotes(data)
}
return (
<div>
</div>
)
}
export default NotesListPage
uj5u.com熱心網友回復:
你不是在呼叫你的函式“getNotes”
我會這樣做,它在 Effect 掛鉤中獲取您的資料并將其設定在您的狀態掛鉤中。
import React, { useState, useEffect } from 'react'
const NotesListPage = () => {
let [notes, setNotes] = useState([])
useEffect( async () => {
const response = await fetch('http://127.0.0.1:8000/api/notes/')
.then(response => response.json())
setNotes(response)
}, [])
console.log(notes)
return (
<div>
</div>
)
}
export default NotesListPage
*編輯
更清潔的方法是在單獨的函式中獲取執行相同的操作,并在您的效果鉤子中呼叫該函式(請參閱上面的其他答案*)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/351080.html
標籤:javascript 反应 姜戈 接口
上一篇:Django多用戶型別遷移錯誤
