【问题标题】:conditional rendering at empty response of API in react jsreact js中API空响应的条件渲染
【发布时间】:2019-06-26 21:14:25
【问题描述】:

我正在构建一个小的 react js 应用程序,用户可以在其中选择一些过滤器并获得相应的响应。对于用户选择的某些值,从数据库中找不到任何内容,我想显示“未找到”消息。

我尝试使用不产生结果的 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)  
            }                                                                    
        })

我在控制台上收到回复。我做错了什么?

【问题讨论】:

    标签: reactjs api axios conditional-rendering


    【解决方案1】:

    声明一个新的状态变量

     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>
        )
    }
    

    【讨论】:

    • 如果我将它放入渲染返回中,那么即使没有选择任何内容,也会显示此消息。
    • @Hemadari,非常感谢您的帮助。我最终只是以稍微不同的方式使用了你的建议。
    • @Ruchit Dalwadi 欢迎您。请看看我更新的答案。您可以这样做,因此只有在您选择时才会显示任何找到的内容
    • 完美。非常感谢。
    【解决方案2】:

    在没有找到任何内容的情况下注销 res.data 对象。它可能不是您的代码假定的空数组,但可能包含一些消息,表明数据库中没有任何内容与您的查询匹配。您需要检查这一点,而不是简单地检查 !res.data。

    【讨论】:

    • 我只这样做了。对于条件 !res.data.length 我在控制台上记录了数据。它出现在控制台上,但是当我返回 div 时,它没有出现。
    猜你喜欢
    • 2017-11-22
    • 2019-12-18
    • 2017-04-04
    • 1970-01-01
    • 2016-02-23
    • 2021-05-22
    • 1970-01-01
    • 2020-07-24
    • 2020-12-19
    相关资源
    最近更新 更多