【发布时间】:2017-10-29 08:07:33
【问题描述】:
所以我正在使用 react 构建一个应用程序,但我的列表没有显示在 render() 上。我有我的父组件,并且有一个来自 SearchResult 的组件列表。这是我的代码:
class CreateBookGroup extends Component {
constructor(props) {
super(props);
this.state = {
titleToSearch: "",
searchResults: []
}
}
new Promise((resolve, reject) => {
let searchBook = this.searchFormatter();
console.log("Search book is " + searchBook);
searchForBook(searchBook, resolve, reject);
}).then((res, err) => {
if (err) {
return console.error(err);
}
console.log(res.body);
for (let i = 0; i < res.body.items.length; i++) {
let smallThumbnail = null;
if (res.body.items[i].volumeInfo.imageLinks) {
smallThumbnail = res.body.items[i].volumeInfo.imageLinks.smallThumbnail;
}
let resultToAdd = {
bookCover: smallThumbnail,
bookTitle: res.body.items[i].volumeInfo.title,
bookAuthors: res.body.items[i].volumeInfo.authors,
bookDescription: res.body.items[i].volumeInfo.description
}
this.state.searchResults.push(resultToAdd);
}
});
}
render() {
const searchBookRes = this.state.searchResults.map((result) => {
<SearchResult
bookCover={result.bookCover}
bookTitle={result.bookTitle}
authorName={result.bookAuthors}
bookDescription={result.bookDescription}
/>
});
console.log(searchBookRes.length);
return (
<div className="GlobalAlignment">
<Header/>
<Container>
<Row>
<Col lg={12}>
<h1>Create a group</h1>
<div className="bookGroupDiv">
<input
type="text"
className="searchText"
required
name="bookSearch"
onChange={this.handleChange.bind(this, "titleToSearch")}
placeholder="Search for a title"/>
<button className="btnStandard searchBtn" onClick={this.searchGoogleBookApi.bind(this)}>Search</button>
</div>
{searchBookRes}
..................................
我什至尝试过预设状态,以便页面最初打开时看起来像这样:
constructor(props) {
super(props);
this.state = {
titleToSearch: "",
searchResults: [{bookTitle: "Sample", bookCover: "Cover", bookAuthors: "Author", bookDescription: "This is the description"}]
}
}
但是,{searchBookRes} 仍然没有显示我的任何列表项,即使它们在我将它们记录到控制台时出现。
另外,我已经手动将测试值输入到我的子组件中,并像这样直接将其放入组件中(这可以很好地传递道具):
return (
<div className="GlobalAlignment">
<Header/>
<Container>
<Row>
<Col lg={12}>
<h1>Create a group</h1>
<div className="bookGroupDiv">
<input
type="text"
className="searchText"
required
name="bookSearch"
onChange={this.handleChange.bind(this, "titleToSearch")}
placeholder="Search for a title"/>
<button className="btnStandard searchBtn" onClick={this.searchGoogleBookApi.bind(this)}>Search</button>
</div>
<SearchResult
bookCover={'Test cover'}
bookTitle={'test title'}
authorName={'test author'}
bookDescription={'test description'}
/>
因此,由于这可以很好地传递道具并显示组件,因此我知道 SearchResult 组件没有问题。有谁看到我做错了什么?很长一段时间后我回来做出反应,但无法弄清楚为什么会出现这个问题。谢谢你的帮助。
【问题讨论】:
标签: javascript html reactjs components