如何根据 ReactJS 中的响应获取 json 数据并渲染组件(列表)

how to fetch json data and render component (List) according to the response in ReactJS

我想从 /list 端点加载图书列表(图书文件)并在 <ul> 中列出它们。我创建了一个列表组件,然后在 index.jsx 上导入它。但它不起作用。如何使用从服务器获取的 json 数据渲染组件?

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.books。您的数据实际上可能在数据中,而不是 data.books。 data.books 可能是一个字符串,您可能需要 JSON.parse 将其转换为数组。

请关注linkhttps://codesandbox.io/s/2p5p0n4lpn

只需使用三元运算符 this.state.files 检查数据是否可用。如果数据可用则渲染。

{this.state.files ? this.state.files.map(书 => { return{book.userId}; }) : }