Javascript 反应状态更改返回时不显示更改
我有一个应用程序,在用户书架上列出书籍,然后在随后的搜索页面上列出。 用户转到搜索页面,找到一个标题并选择一个书架,以便将标题搁置在其上。当他们返回主页时,该标题应显示在正确的书架上 该功能的工作原理是对对象进行更改,但当我在浏览器中单击“主页”按钮或“上一步”按钮时,在刷新浏览器之前不会显示更改 我需要做什么来确保在用户浏览主页时显示此更改 我已将大部分代码放入Javascript 反应状态更改返回时不显示更改,javascript,reactjs,Javascript,Reactjs,我有一个应用程序,在用户书架上列出书籍,然后在随后的搜索页面上列出。 用户转到搜索页面,找到一个标题并选择一个书架,以便将标题搁置在其上。当他们返回主页时,该标题应显示在正确的书架上 该功能的工作原理是对对象进行更改,但当我在浏览器中单击“主页”按钮或“上一步”按钮时,在刷新浏览器之前不会显示更改 我需要做什么来确保在用户浏览主页时显示此更改 我已将大部分代码放入 App.js import React, { Component } from 'react' import ListBooks f
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
import React,{Component}来自“React”
从“./ListBooks”导入ListBooks
从“./SearchBooks”导入SearchBooks
从“/utils/BooksAPI”导入*作为BooksAPI
从“react router dom”导入{Route}
类BooksApp扩展组件{
状态={
书籍:[]
}
componentDidMount(){
BooksAPI.getAll()
.然后((书)=>{
此.setState(()=>({
书
}))
})
}
UpdateSelf=(书籍、书架)=>{
const bookFromState=this.state.books.find(b=>b.id==book.id);
如果(bookFromState){
//更新现有
bookFromState.shelf=书架;
this.setState(currentState=>({
图书:currentState.books
}));
}否则{
//添加新的
this.setState(prevState=>({
图书:prevState.books
}));
}
BooksAPI.update(书籍、书架);
};
render(){
返回(
(
)} />
(
)} />
)
}
}
导出默认BookApp
所以我检查了你的代码。实际上,您在更新状态时遇到了问题。从搜索屏幕中选择书籍后,书籍
没有更改。以下是您的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:我可能留下了一些
控制台.log
语句。希望这不是一个问题,你会收拾残局 您的沙盒不工作如果不工作,只需单击沙盒浏览器窗口中的黄色选项卡。不知道为什么会出现这个错误,但它只出现在沙盒中!干杯,伙计,这是正确的