首页 > 解决方案 > 返回时反应状态更改不显示更改

问题描述

我有一个应用程序,它在用户书架上列出书籍,然后在随后的搜索页面上列出。用户进入搜索页面,找到一个标题并选择一个架子来放置标题。当他们返回主页时,该标题应显示在正确的架子上。

该功能的工作原理是对对象进行了更改,但是当我单击浏览器中的主页按钮或后退按钮时,在我刷新浏览器之前更改不会显示。

我需要做些什么来确保在用户浏览到主页时显示此更改?

我已将大部分代码放入Codesandbox

App.js

import React, { Component } from 'react'
import ListBooks from './ListBooks'
import SearchBooks from './SearchBooks'
import * as BooksAPI from './utils/BooksAPI'
import { Route } from 'react-router-dom'

class BooksApp extends Component {

  state = {
    books: []
  }

  componentDidMount() {
    BooksAPI.getAll()
    .then((books) => {
      this.setState(() => ({
        books
      }))
    })
  }

  updateShelf = (book, shelf) => {
    const bookFromState = this.state.books.find(b => b.id === book.id);
    if (bookFromState) {
      // update existing
      bookFromState.shelf = shelf;
      this.setState(currentState => ({
        books: currentState.books
      }));
    } else {
      // add new one
      this.setState(prevState => ({
        books: prevState.books
      }));
    }
    BooksAPI.update(book, shelf);
  };

  render() {
    return (
      <div>
        <Route exact path='/' render={() => (
          <ListBooks
          books={this.state.books}
          onUpdateShelf={this.updateShelf}
          />
        )} />
        <Route exact path='/search' render={() => (
          <SearchBooks
          books={this.state.books}
          onUpdateShelf={this.updateShelf}
          />
        )} />
      </div>
    )
  }
}
export default BooksApp

标签: javascriptreactjs

解决方案


所以我检查了你的代码。实际上,您在更新状态时遇到了问题。books从搜索屏幕中选择一本书后,它并没有改变。这是您的 App.js 中的代码:

updateShelf = (book, shelf) => {
  console.log(book, shelf)
  const bookFromState = this.state.books.find(b => b.id === book.id);
  if (bookFromState) {
    // update existing
    bookFromState.shelf = shelf;
    this.setState(currentState => ({
      books: currentState.books
    }));
  } else {
    // add new one
    // the following lines of yours were different
      book.shelf = shelf;
      this.setState(prevState => ({
        books: prevState.books.concat(book)
    }));
  }
  BooksAPI.update(book, shelf);
};

因此,您只需books: prevState.books将书连接到 prev 状态,而不是实际连接。就在此之前,书架必须更改为您通过的书架。PS:我可能会留下一些console.log陈述。希望这不是问题,你会清理烂摊子。


推荐阅读