React.js 组件在获取后从未刷新

React.js component never refreshed after fetch

Visual Studio React.js 入门套件

不知道为什么处理完fetch后显示组件没有刷新? 'setResults' 函数被正确调用,并且数据被设置,但图库组件从未获得更新的数据。我如何实现这一目标?刚开始的组件是否设置错误?

googleapi的书api例如用'harry potter'搜索。 我得到 10 个结果。 但是画廊永远不会用找到的数据更新。 我需要触发什么才能使 'gallery' 显示新找到的数据?

我猜是因为 fetch.then.then 异步在后台运行,图库组件没有以某种方式得到通知?我对反应和异步调用一无所知。

主要成分:

'use strict';

var React = require('react');
var BookGallery = require('./BookGallery.jsx');

var BookSearch = React.createClass({
  getInitialState() {
    return {
      query: '',
      books: []
    };
  },
  setResults(value) {
    this.books = value.items;
    if (this.books) {
      console.log('count of books found: ' + this.books.length);
    } else {
      console.log('nothing found!');
    }
  },
  search() {
    const BASE_URL = 'https://www.googleapis.com/books/v1/volumes?q=';

    if (this.query) {
      console.log("Do the search with " + this.query);

      fetch(BASE_URL + this.query, { method: 'GET' })
        .then(response => response.json())
        .then(json => this.setResults(json));


    } else {
      console.log("Nothing to search for...");

    }
  },

  render() {
    return (

      <div className="Global">
        <h3>Book Search</h3>
        <p>
          <input
              type="search"
              id="inputBookTitle"
              onChange={event => this.query = event.target.value}
              onKeyUp={event => {
                if (event.key == "Enter") {
                  this.search();
                }
              }}
            />
          <span style={{ border: '1px solid garkgrey', padding : '5px', background: 'lightgray' }} >
            <span className="glyphicon glyphicon-search" onClick={() => this.search()} ></span>
          </span>
        </p> 
        <BookGallery list={this.books}/>
      </div>
    );
  }
});

module.exports = BookSearch;

然后是图库组件:

'use strict';

var React = require('react');

var BookGallery = React.createClass({
  getInitialState() {
    return {
      books: []
    };
  },
  rate() {

    console.log("Rate the book");
  },
  render() {
    this.books = this.props.list || [];
    console.log(this.books);
    return (
      <div id="bookContainer" >
        <h4>Results:</h4>
        <ul id="gallery">
          {
            this.books.map((item, index) =>
              <li key={index}>{book}</li>
            )
          }
        </ul>
      </div>
    );
  }
});

module.exports = BookGallery;
this.books = value.items;

应该是

this.setState({books: value.items});

React 根据 setState 调用决定何时渲染状态,而不仅仅是改变状态。

此外,您似乎假设状态存在于 this,但事实并非如此,它存在于 this.state,因此无论您指的是 this.books 进行渲染, 你应该指的是 this.state.books.