儿童组件没有重新渲染道具的变化

时间:2017-08-25 00:53:49

标签: javascript reactjs jsx

这是父组件:

    state = {
    books: undefined
  }

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

  filterBooks() {
    this.currentlyReading = this.state.books.filter((book) => book.shelf === 'currentlyReading');
    this.read = this.state.filter((book) => book.shelf === 'read');
    this.wantToRead = this.state.filter((book) => book.shelf === 'wantToRead');
  }

  render() {
    return (
      <div className="app">
        <Route path="/search" component={SearchBook} />
        <Route exact
          path="/"
          render={() => <BookScreen
            currentlyReading={this.currentlyReading}
            read={this.read}
            wantToRead={this.wantToRead}
          />} />
      </div>
    )
  }

我希望在调用filterBooks并且组件应该重新渲染之后,BookScreen组件的props会更改,但它不会。我做错了什么?

2 个答案:

答案 0 :(得分:1)

您可以尝试这样做,只需像这样更新图书状态:

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

这将导致重新渲染。但是,由于您未直接使用州填充子组件,因此我们需要在filterBooks()方法中调用render()

render() {
   this.filterBooks()
return (
  <div className="app">
    <Route path="/search" component={SearchBook} />
    <Route exact
      path="/"
      render={() => <BookScreen
        currentlyReading={this.currentlyReading}
        read={this.read}
        wantToRead={this.wantToRead}
      />} />
  </div>
  )
}

对该方法的调用将更新您作为道具传递给子组件的数据。

答案 1 :(得分:1)

在我看来,目前仍然遵循React方式的最佳方法是:在获得books数据后,仅调用1个函数,此函数将处理所有内容并在完成后更新状态(我们传递{ {1}} object as parameter),如下所示:

books

如果您有任何错误,请随时在此发布,然后我们可以一起完成!

======

添加了有关作者原始代码不起作用的解释:

基于我对React和JS的一点经验:

设置新状态时,可能需要一些时间(可能需要100-300毫秒,这就是您使用语法 componentDidMount() { BooksAPI.getAll().then(books => { this.filterBooks({books}); }); } filterBooks = (books) => { this.currentlyReading = books.filter((book) => book.shelf === 'currentlyReading'); this.read = books.filter((book) => book.shelf === 'read'); this.wantToRead = books.filter((book) => book.shelf === 'wantToRead'); this.setState({ books: books }); }

执行原始this.filterBooks的原因

=&GT;这似乎是正确的,这意味着在设置了this.setState({books},this.filterBooks)的新状态后,您可以访问books函数。)

但是:在设置filterBooks的新状态后,将重新呈现该页面,并且books将被执行(可能同时=>不确定哪一个首先结束,例如,如果filterBooksthis.currentlyReading的结果完全设定之前发生render()render()仍然未定义{/ 1}}。

换句话说,React是Javascript,Javascript的异步很麻烦!