React - adding a component to a Map function not adding

I want to add components to dom through the array display function. {books.map((book) => <Book/>)}

However, this doesn’t add anything, it looks like the array of books is empty? I printed books using {console.log(books)}, and it is not empty. What is wrong here? I added my render function.

  render() {
    let books = this.state.books;
    return (<div className="bookshelf">
      <h2 className="bookshelf-title">{this.titles[this.props.shelf]}</h2>
      <div className="bookshelf-books">
        <ol className="books-grid">
          {books.map((book) => <Book/>)}
        </ol>
      </div>
    </div>)
  }

For any information, I get the values ​​of the book through an api call.

  componentWillMount() {
    BooksAPI.getAll().then((books) => {
      books.forEach((book) => {
        if (this.state.shelf === book.shelf){
          // console.log(book);
          this.state.books.push(book);
        }
      })
    })
  }

Thank you if you understand what is happening.

+4
source share
3 answers

What is wrong is that you are a directly mutatingstate and it is not displayed repeatedly, so the change is not reflected in your DOM. use setStateto update state

componentWillMount() {
    BooksAPI.getAll().then((books) => {
      const tempBooks = [];
      books.forEach((book) => {
        if (this.state.shelf === book.shelf){
          // console.log(book);
          tempBooks.push(book);
        }
      })
      this.setState(prevState => ({books: [...prevState.books, ...tempBooks]}))
    })
  }
+2
source
render() {
    let books = this.state.books;
    return (<div className="bookshelf">
      <h2 className="bookshelf-title">{this.titles[this.props.shelf]}</h2>
      <div className="bookshelf-books">
        <ol className="books-grid">
          {books.map((book) => return(<Book/>))}
        </ol>
      </div>
    </div>)
  }
+2
source

. .

  componentWillMount() {
    BooksAPI.getAll().then((books) => {
      books.forEach((book) => {
        if (this.state.shelf === book.shelf) {
          this.setState(prevState => ({books: [...prevState.books, book]}))
        }
      })
    })
  }
0

Source: https://habr.com/ru/post/1689664/


All Articles