models.py
class Book(models.Model):
name = models.CharField(max_length=100, unique=True)
author = models.CharField(max_length=64)
passcode = models.CharField(max_length=80)serializers.py
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = '__all__'views.py
class GetBooks(APIView):
def get(self, request):
books = models.Book.objects.all()
data = serializers.BookSerializer(books, many=True).data
return Response(data, status=status.HTTP_200_OK)urls.py
urlpatterns = [
path('get-books', views.GetBooks.as_view(), name='get-books')
]Main.js
import React, { Component } from 'react'
export default class Main extends Component {
constructor(props){
super(props)
this.state = {
books: ''
}
this.getBooks()
}
getBooks() {
fetch('http://127.0.0.1:8000/api/get-books') // go down to see the data
.then((response) => {
const books = response.json()
console.log(books) // go down to see the output <---- !!
this.setState({
books: books
})
})
}
render() {
return (
<div>
// for book in books show book.name, book.author ...
</div>
)
}
}从(http://localhost/api/get-books)获取的书籍数据
[
{
"id": 1,
"name": "book1",
"author": "author1",
"passcode": "123"
},
{
"id": 2,
"name": "book2",
"author": "auhthor2",
"passcode": "123"
}
]console.log(data)
Promise { <state>: "pending" }
<state>: "fulfilled"
<value>: Array [ {…}, {…} ]
0: Object { id: 1, name: "book1", author: "author1", … }
1: Object { id: 2, name: "book2", author: "author2", … }
length: 2
<prototype>: Array []我想遍历所有的书籍并显示给用户,获取的数据作为数组返回,但是我不能从this.state.books访问它(我最近开始使用react和django,所以请宽恕.)
发布于 2021-07-11 14:25:09
我找到了一个解决方案
Main.js
import axios from 'axios'
import React, { Component } from 'react'
import Books from './Books'
export default class Main extends Component {
constructor(props){
super(props)
this.state = {
books: []
}
}
componentDidMount() {
axios.get('http://localhost:8000/api/get-books')
.then(res => {
this.setState({
books: res.data
})
})
}
render() {
return (
<div>
<Books books={this.state.books} />
</div>
)
}
}Books.js
import React from 'react'
const Books = ({books}) => {
return (
<div>
{books.map(book => (
<div>
<h1>{book.name}</h1>
<small>{book.author}</small>
</div>
))}
</div>
)
}
export default Books--我只使用axios,将数据放入数组并发送给Book.js,然后使用.map()迭代它们!
https://stackoverflow.com/questions/68335867
复制相似问题