简体   繁体   English

状态更改后,UI不会呈现

[英]UI does not render after state is changed

I have an app (project in Udacity) in React which display books on my shelves according to categories: Currently Reading , Want to Read and Read . 我在React有一个应用程序(Udacity中的项目),该应用程序根据以下类别在书架上显示书籍: 当前阅读想要阅读阅读 Every time I change the category say from Want to Read to Currently Reading the book will move to the right category and in this case it would be Currently Reading. 每次我将类别从“想阅读”更改为“正在阅读”时,该书都会移至正确的类别,在这种情况下,它将是“当前阅读”。 My code works on this one with no problem. 我的代码可以毫无问题地在此代码上运行。 However, you can also search from the vast library of books wherein you could move to your shelf, by default the category is None, although you could include the existing books in your shelf as part of being search (aside from the main library of books). 但是,您也可以从庞大的图书库中搜索,您可以将其移至书架,默认情况下类别为“无”,尽管您可以在搜索中将书架中的现有图书包括在内(除了主图书库外) )。 Now, my problem is this, if I move from None to Want To Read category for example my UI does not change after I click the back button that brought me back to the main page (ie App.js). 现在,我的问题是这样的,例如,如果我从“ 无”转到“ 想要阅读”类别,则在单击使我回到主页(即App.js)的后退按钮后,我的UI不会更改。 When I do however, change of category in the main, I have no problem. 但是,当我主要改变类别时,我没有问题。 Also my function for updating the Book Shelf in App.js when called does not show any error in the console. 此外,我在调用App.js中更新Book Shelf的功能时,在控制台中未显示任何错误。

I have the following components: 我具有以下组件:

 App
  |
  |--BooksSearch
  |--BooksList
  |     |--BookShelf
  |--BooksSearchPage
        |--BookShelf

The BooksList and BooksSearch displays the books and the search button respectively in the main page (ie App.js). BooksListBooksSearch在主页(即App.js)中分别显示书籍和搜索按钮。 The BooksSearchPage allows user to search books from the library to move into the shelves. BooksSearchPage允许用户从图书馆搜索书籍以移入书架。 The BookShelf displays the list of books whether they are in the shelves or in the library. BookShelf会显示书籍列表,无论它们是在书架中还是在图书馆中。

This is my App.js 这是我的App.js

class App extends React.Component {

 state = {
 mybooks : [], 
 showSearchPage: false
}

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

toCamelShelf(Shelf) {
 if (Shelf==="currentlyreading") return "currentlyReading"
 if (Shelf==="wanttoread") return "wantToRead"
 return Shelf
}

updateBookShelf = (mybook, shelf) => {
shelf=this.toCamelShelf(shelf)
BooksAPI.update(mybook, shelf).then(
this.setState((state)=>({      
    mybooks: state.mybooks.map((bk)=>bk.id === mybook.id ? 
    {...bk, shelf:shelf} : bk)
 })))}

render() {
 return (
   <div className="app">
     {this.state.showSearchPage ? (
       <Route path='/search' render={({history})=>(
        <BooksSearchPage mybooks={this.state.mybooks} onSetSearchPage={
            ()=>{ this.setState({showSearchPage:false});
                  history.push("/");
              }}
              onUpdateBookShelf={this.updateBookShelf}
            />
      )} />
    ) : (
      <Route exact path='/' render={()=>(
        <div className="list-books">
          <div className="list-books-title">
            <h1>My Reads</h1>
          </div>
          <BooksList mybooks={this.state.mybooks} 
            onUpdateBookShelf={this.updateBookShelf}/>
          <BooksSearch onSetSearchPage={()=>this.setState({showSearchPage:true})}/>
        </div>
      )} />           
    )}
  </div>
  )
 }
}

export default App

And since the code is too long, I included my repo in Github. 而且由于代码太长,我将我的存储包含在Github中。 I am very new to ReactJS and have been debugging this problem for the last 3 days but to no avail. 我对ReactJS还是很ReactJS ,最近3天一直在调试此问题,但无济于事。

I'm having a hard time understanding the app enough to know why exactly, but it sounds like its a state issue. 我很难充分理解该应用程序,以确切了解其原因,但这听起来像是状态问题。

If you navigate away and come back, or click something and it doesn't update properly, the state isn't being updated at that moment (that event) or the state wasn't saved correctly right before that event. 如果您导航离开并返回,或者单击某些内容后无法正确更新,则表示该状态(该事件)当时未更新,或者该事件发生之前该状态未正确保存。

As soon as you reproduce the problem event, ask yourself "what was the state right before I did this?" 重现问题事件后,请问自己“在我这样做之前,状态是什么?” and "why is the state how it is now?" 以及“为什么状态现在如此?”

  1. Did you forget to update the state? 您忘了更新状态吗?
  2. Is it getting the wrong state from somewhere? 是从某个地方获取了错误的状态吗?
  3. Did you call this.setState({ something }) ? 您是否调用过this.setState({ something })
  4. Did you overwrite the state instead of adding to it? 您是否覆盖状态而不是添加状态?
  5. Is there a missing state update? 是否缺少状态更新?

On both pages, right before and right after, add in the render method: console.log(this.state) and if needed, console.log(this.props) . 在这两个页面上的前后添加渲染方法: console.log(this.state)并在需要时添加console.log(this.props) I think you will see the problem if you look there. 我认为,如果您在那里看,就会看到问题。 The question is how exactly did it get like that? 问题是,它到底是怎么得到的? Re-visit all your state updates. 重新访问所有状态更新。

If you navigate away and come back, where does it get that state from? 如果您导航离开并返回,它将从何处获得该状态? Why is that data in there? 为什么这些数据在那里?

Remember, React is a state machine. 记住,React是一个状态机。 State is an object that has a snapshot of data every time you look at it. 状态是一个对象,每次查看时都有数据快照。 It's like looking at a piece of paper with all your data on it. 就像看一张纸上所有数据一样。 If you leave the room and come back and the data isn't there, what updated your state and made it go away? 如果您离开房间再回来但数据不在那里,是什么更新了您的状态并使其消失了? or why didn't it get added to your state? 还是为什么不将其添加到您的州? That mechanism there is causing your problem. 那里的机制正在导致您的问题。

I see a few spots in your code to focus on: 我在您的代码中看到了一些重点:

BooksAPI.update(mybook, shelf).then(
this.setState((state)=>({      
    mybooks: state.mybooks.map((bk)=>bk.id === mybook.id ? 
    {...bk, shelf:shelf} : bk)
 })))}

and

<BooksSearchPage mybooks={this.state.mybooks} onSetSearchPage={
        ()=>{ this.setState({showSearchPage:false});
              history.push("/");
          }}
          onUpdateBookShelf={this.updateBookShelf}

and

<BooksList mybooks={this.state.mybooks} 
            onUpdateBookShelf={this.updateBookShelf}/>
          <BooksSearch onSetSearchPage={()=>this.setState({showSearchPage:true})}/>

also right up here: 也就在这里:

class App extends React.Component {
  state = {
  mybooks : [], 
  showSearchPage: false
 }

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

One of them is acting too strongly or one of them isn't updating at the right time, or data is getting overwritten, I suspect. 我怀疑其中之一表现得过强,或者其中之一没有在正确的时间更新,或者数据被覆盖。

The console.log() should be most helpful. console.log()应该最有帮助。 If your data is missing. 如果您的数据丢失。 Make it show up there at that time and the problem will go away :) (PS that setState on componentDidMount looks a little suspect). 到那时显示它,问题将消失:)(PS上componentDidMount上的setState看起来有点可疑)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM