我有一个应用程序,用于在用户书架上列出书籍,然后在后续搜索页面上列出。 用户进入搜索页面,找到标题并选择要搁置的标题的架子。当他们回到主页时,这个标题应该显示在正确的架子上。
该功能的作用是对对象进行更改,但是当我单击浏览器中的主页按钮或后退按钮时,在我刷新浏览器之前,更改不会显示。
当用户浏览主页时,我需要做些什么才能确保显示此更改?
我已将大部分代码放入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
答案 0 :(得分:0)
所以我检查了你的代码。实际上你有更新你的状态的问题。从搜索屏幕中选择书籍后,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
而不是实际将这本书连接到普通状态。就在此之前,书架必须改为你通过的书架。
PS:我可能已经留下了一些console.log
陈述。希望这不是问题,你会清理混乱。