I'm trying to display the list of results taken from the response of wikipedia API.
If the response doesn't show any list, it should show a different message. I am trying to do a conditional rendering.
以下是代码:
getData(e) {
e.preventDefault();
var search = e.target.search.value;
var wikipediaEndPoint = "https://en.wikipedia.org/w/api.php?format=json&origin=*&action=query&generator=search&gsrnamespace=0&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch="+search;
var wikipediaUrl = "https://en.wikipedia.org/?curid=";
fetch(wikipediaEndPoint)
.then(data => {
return data.json();
}).then(data => {
var objectList = (data.hasOwnProperty("query")) ? data.query.pages : "";
let resultList;
if(objectList !== ""){
resultList = Object.keys(objectList).map(function(key, index) {
return (
<div className="item" key={objectList[key].pageid}>
<a href={wikipediaUrl+objectList[key].pageid}>
<h1>{objectList[key].title}</h1>
<p>{objectList[key].extract}</p>
</a>
</div>
)
});
} else {
resultList = (function() {
return (
<div className="item" key={1}>
<p>No results!</p>
</div>
)
});
}
this.setState({search: resultList});
})
}
结果如下所示:<div className="items">{this.state.search}</div>
当搜索字段关键字找到一些结果时,它可以正常工作,但是,在相反的情况下,控制台会返回错误(或警告):
Warning: Functions are not valid as a React child. This may happen if
Where is the error? Am I doing the conditional rendering the right way?
谢谢