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;