在 React js 中 API 的空响应条件渲染
conditional rendering at empty response of API in react js
我正在构建一个小的 React js 应用程序,用户可以在其中 select 一些过滤器并获得相应的响应。对于用户 selected 的某些值,从数据库中找不到任何内容,我想显示 "nothing found" 消息。
我尝试使用 if & else 条件运算符,但没有产生结果。下面是代码。
.then(res => {
if(!res.data.length){
return(
<div>
<h1>nothing found.</h1>
</div>
)
}
else{
this.setState({ data: res.data,urlList:[] })
console.log(this.state)
}
})
现在如果我这样做
.then(res => {
if(!res.data.length){
console.log('nothing found')
}
else{
this.setState({ data: res.data,urlList:[] })
console.log(this.state)
}
})
我在控制台上收到了回复。我做错了什么?
注销 res.data 对象,以防找不到任何东西。它可能不是您的代码假定的空数组,但可能包含一些消息,表明数据库中没有任何内容与您的查询匹配。您需要检查这个而不是简单地检查 !res.data.
声明一个新的状态变量,例如
constructor(props){
super(props);
this.state = {
noData: ''
}
}
这里
.then(res => {
if(!res.data.length){
this.setState({noData: 'nothing found'});
console.log('nothing found')
}
else{
this.setState({ data: res.data,urlList:[], noData: '' })
console.log(this.state)
}
})
并且在渲染中只显示 this.state.noData
render(){
return(
<div>
<h1>{this.state.noData}</h1>
</div>
)
}
我正在构建一个小的 React js 应用程序,用户可以在其中 select 一些过滤器并获得相应的响应。对于用户 selected 的某些值,从数据库中找不到任何内容,我想显示 "nothing found" 消息。
我尝试使用 if & else 条件运算符,但没有产生结果。下面是代码。
.then(res => {
if(!res.data.length){
return(
<div>
<h1>nothing found.</h1>
</div>
)
}
else{
this.setState({ data: res.data,urlList:[] })
console.log(this.state)
}
})
现在如果我这样做
.then(res => {
if(!res.data.length){
console.log('nothing found')
}
else{
this.setState({ data: res.data,urlList:[] })
console.log(this.state)
}
})
我在控制台上收到了回复。我做错了什么?
注销 res.data 对象,以防找不到任何东西。它可能不是您的代码假定的空数组,但可能包含一些消息,表明数据库中没有任何内容与您的查询匹配。您需要检查这个而不是简单地检查 !res.data.
声明一个新的状态变量,例如
constructor(props){
super(props);
this.state = {
noData: ''
}
}
这里
.then(res => {
if(!res.data.length){
this.setState({noData: 'nothing found'});
console.log('nothing found')
}
else{
this.setState({ data: res.data,urlList:[], noData: '' })
console.log(this.state)
}
})
并且在渲染中只显示 this.state.noData
render(){
return(
<div>
<h1>{this.state.noData}</h1>
</div>
)
}