javascript - 返回时反应状态更改不显示更改
问题描述
我有一个应用程序,它在用户书架上列出书籍,然后在随后的搜索页面上列出。用户进入搜索页面,找到一个标题并选择一个架子来放置标题。当他们返回主页时,该标题应显示在正确的架子上。
该功能的工作原理是对对象进行了更改,但是当我单击浏览器中的主页按钮或后退按钮时,在我刷新浏览器之前更改不会显示。
我需要做些什么来确保在用户浏览到主页时显示此更改?
我已将大部分代码放入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
解决方案
所以我检查了你的代码。实际上,您在更新状态时遇到了问题。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
陈述。希望这不是问题,你会清理烂摊子。
推荐阅读
- .net-core - .Net 或 .Net Core 中是否有等效的 Spring Cloud Stream?
- c++ - Protobuf:了解 proto 文件的编译输出
- javascript - 不能在父级的 [ngClass] 逻辑中使用子级输入值
- ruby-on-rails - rails capistrano deploy 成功,但我无法访问我的部署 rails 主页
- c# - C# LibreOffice 进程不等待退出
- bash - 为什么 pkill 没有杀死命令 python blink_led.py&
- r - 如何重命名数据框中的单个列
- c# - 试图让玩家旋转垂直于模型的网格。统一
- python - Python csvwriter 未写入 csv 文件
- typo3 - TYPO3 9.5 显示 pdf 文件