当我看不到 api 结果时,我需要显示未找到的数据


  • 当我输入1sport1时,我看到了结果。
  • 当我输入 1sport12 时,我没有看到任何结果。
  • 所以该类型我需要显示未找到 dta。
  • 并在清除所有时,它应该清除文本框。
  • 但问题是这条线console.log("resp.json()--->", resp.json().[[PromiseValue]]);
  • 我以为当长度为 0 时,我将显示未找到数据。
  • 但我收到此错误。/src/searchbar.js: Unexpected token (31:48)
  • 我正在评论以下行,以便您可以在浏览器中看到输出// console.log("resp.json()--->", resp.json().[[PromiseValue]]); // display: this.state.noData ? "" : "none"
  • 你能告诉我当没有来自 API 的数据时如何显示未找到的数据吗?
  • 在下面提供我的代码片段和沙盒。

https://codesandbox.io/s/jovial-cdn-14o1w

getQuery = async (type = "", search_tag = "") => {
var url = "https://hn.algolia.com/api/v1/search?tags=";
const resp = await fetch(`${url}${type}&query=${search_tag}`);
// console.log("resp.json()--->", resp.json().[[PromiseValue]]);
return resp.json();
};
render() {
console.log("this.state.noData--->", this.state.noData);
return (
<div>
<input type="text" onChange={this.searchByKeyword} />
<p
style={
{
// display: this.state.noData ? "" : "none"
}
}
>
No data found
<p>clear all</p>
</p>
{/* <Scroll />  */}
</div>
);

您可以使用 JSX 上的条件呈现来实现此目的。

将您的代码更改为以下内容,它将起作用。

<SearchBar onFetch={this.onFetch} />
{this.state.data && this.state.data.length > 0 ? 
this.state.data.map((item) => <div key={item.objectID}>{item.title}</div>) :
<p>no data</p>}

我分叉了沙盒,在这里

最新更新