0

Visual Studio React.js 入门工具包

不知道为什么 fetch 处理后显示组件没有刷新?正确调用了“setResults”函数,并设置了数据,但图库组件永远不会获取更新的数据。我如何实现这一目标?刚开始时组件是否设置错误?

例如,使用“哈利波特”搜索 googleapis book api。我得到了 10 个结果。但是画廊永远不会用找到的数据更新。我需要触发什么才能使“图库”显示新发现的数据?

我猜是因为 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;
4

1 回答 1

3
this.books = value.items;

应该

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

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

此外,您似乎假设状态存在this,它不存在,它存在this.state,所以无论您指的this.books是渲染,您都应该指的是this.state.books.

于 2017-12-14T20:49:34.567 回答