我想从 /list
加载图书列表(图书文件)端点并将它们列在 <ul>
中。我创建了一个列表组件,然后将其导入 index.jsx
。但这不起作用。如何使用从服务器获取的 json 数据在 body 中渲染组件?
list.component.jsx:
import React from 'react'
class List extends React.Component {
constructor() {
super()
this.state = { files: [] }
}
componentDidMount() {
let files = []
fetch('/books', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ dir: '/' })
})
.then(response => response.json())
.then(data => {
this.setState({ files: data.books })
})
}
render() {
return (
<div>
<h1>Book List</h1>
<ul>
{this.state.files.map(book => {
return <li key={`book-${book.id}`}>{book.name}</li>
})}
</ul>
</div>
)
}
}
export default List
index.jsx:
import List from '../components/list'
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<List/>,
document.body.appendChild(document.createElement('div')),
)
})
我看到“网络”选项卡中提取了“/list”,但浏览器上没有数据。
给出的错误:
list.jsx:31 Uncaught TypeError: this.state.files.map is not a function
at List.render (list.jsx:31)
list.jsx:31 Uncaught (in promise) TypeError: this.state.files.map is not a function
at List.render (list.jsx:31)
最佳答案
您是否在 setState 命令之前直接尝试过 console.log 语句?可能值得检查数据,然后检查数据书籍。您的数据实际上可能位于 data 而不是 data.books 中。 data.books 可能是一个字符串,您可能需要 JSON.parse 将其转换为数组。
关于javascript - 如何在ReactJS中获取json数据并根据响应渲染组件(List),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55609051/