代码之家  ›  专栏  ›  技术社区  ›  Fahad AlDaferi

使用setState更新书架

  •  1
  • Fahad AlDaferi  · 技术社区  · 7 年前

    我有初学者模板,我转换为反应网站学习,我不知道如何使用setState更新书架。在项目中,我有App.js文件,其中有changeself函数,我想使用setState函数来更新当前状态,而不是使用BooksAPI.update函数中的BooksAPI.getAll来完成相同的工作。

    changeShelf(book, shelf) {
        BooksAPI.update(book, shelf).then(() => {
            BooksAPI.getAll().then((books) => {
                this.collectBooks(books)
            })
        })
    }
    

    App.js文件: https://codeshare.io/5wK36x

    https://codeshare.io/adDo9g

    1 回复  |  直到 7 年前
        1
  •  1
  •   Thijs Kramer    7 年前

    首先你得把书从现在的书架上取下来。然后把书放在右边的书架上。

    你可以改变 changeShelf 以下内容:

    getShelfWithoutBook(shelf, book) {
        return shelf.filter(item => item !== book);
    }
    
    changeShelf(book, shelf) {
        this.setState({
            currentlyReadingBooks: this.getShelfWithoutBook(this.state.currentlyReadingBooks, book),
            wantToReadBooks: this.getShelfWithoutBook(this.state.wantToReadBooks, book),
            readBooks: this.getShelfWithoutBook(this.state.readBooks, book)
        });
        if (shelf === 'currentlyReading') {
          this.setState({
            currentlyReadingBooks: this.state.currentlyReadingBooks.push(book)
          });
        } else if (currentShelf === 'wantToRead') {
          this.setState({
            wantToReadBooks: this.state.wantToReadBooks.push(book)
          });
        } else if (currentShelf === 'read') {
          this.setState({
            readBooks: this.state.readBooks.push(book)
          });
        }
    }
    

    这可能可以写得少很多重复,但我希望这样更容易理解。

    编辑:或者你可以重新使用你的 collectBooks

    changeShelf(book, shelf) {
        // collect all books in one list:
        const books = [
            ...this.state.currentlyReadingBooks, 
            ...this.state.wantToReadBooks, 
            ...this.state.readBooks
        ];
        // remove the book you want to change: 
        const booksWithoutThisBook = books.filter(item => item !== book);
        // update the shelf of the current book:
        book.shelf = shelf;
        // re-add the changed book:
        const booksWithUpdatedBook = [...booksWithoutThisBook, book];
        // re-run the collectBooks method:
        this.collectBooks(booksWithUpdatedBook);
    }