简体   繁体   中英

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

I want to load book list (book files) from /list endpoint and list them in <ul> . I created a list component and then import it on index.jsx . But it doesn't work. How can I render component with json data fetched from server in 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')),
  )
})

I see that '/list' fetched in Network tab but no data on the browser.

Errors given:

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)

Have you tried console.log statements directly before the setState command? Might be worth inspecting data and then data.books. Your data might actually be in data and not data.books. data.books might be a string and you may need to JSON.parse it to convert to an array.

Please follow the link https://codesandbox.io/s/2p5p0n4lpn

Just check using ternary operator this.state.files is data available or not. If data is available then render.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM