javascript - 如果没有用户查询的地名,我无法显示 noroom 组件

标签 javascript ajax reactjs

我有一个搜索表单,用户可以在其中搜索地点。如果用户输入的位置在 api(响应对象)中,那么我想显示 Room 组件,否则显示 NoRoom 组件。当我输入 api 中没有的位置时,我的 NoRoom 组件不会显示。

search( query='place' ){
    let url = "http://localhost:8000/api/v1/rental/?place__startswith="+encodeURIComponent(query);
    Request.get(url).then((response) => {
        console.log('response',response.body.objects);
        this.setState({
            place:response.body.objects,
        });
    });
  }

  searchUpdated(term){
    this.search(term);
  }

  render() {
        var margin = { marginTop : '13em' };
        if (this.state.place){
        let location = _.map(this.state.place, (place,id) => {
            return(
                    <Room key={id}
                    slug={place.slug}
                    place={place.place}
                    city={place.city}
                    gallery={place.gallery}
                    property={place.property}/>
                )
            console.log('location',location);
        });
        let gallery = _.map(this.state.place, (place,id) => {
            console.log('place',place.gallery);
            _.map(place.gallery, (image,id) => {
                return(
                        <img src={image.image} class="img-fluid" />
                    )
            });
        });
        return(
            <div className = "container">
                <div className="content text-align-center">
                    <div className="row text-xs-center">
                        <div className="middle-text"  style={margin}>
                            <h1 className="welcome"><span>Rental Space Welcome's you </span></h1>
                            <button ref="test" className="btn how-it-works" onClick={this.handleClick}>Search Space</button>
                        </div>
                    </div>
                </div>
                <div id="mySearch" className="overlay"  onKeyDown={this.handleKeyDown}>
                  <button className="btn closebtn" onClick={this.handleClick}>x</button>
                  <div className="overlay-content">
                        <SearchInput ref="searchInput" className="search-input" onChange={this.searchUpdated} />
                         <div className="container searchList">
                                { location }
                        </div>
                  </div>
            </div>
            </div>
            );
    }
    else{
        return(
            <NoRoom />
            )
    }
    }
}

class Room extends React.Component{
    render(){
        let imageFile = this.props.gallery.map((image) => {
            return(
                    <img src={image.image} className="img-fluid" width="250px" height="250px" />
                );
        });
        return(
                <div className="room">
                     <div className="thumbnail">
                        { imageFile[0] }
                    </div>
                    <h3 className="listingName text-left">
                     <a href = { "/rent/" + this.props.slug }>{this.props.place}</a>
                    </h3>
                    <span className="propertySpan">
                        <i className = "fa fa-home"></i>
                        <span className="property">{this.props.property}</span>
                    </span>
                </div>
            )
    }
}

class NoRoom extends React.Component{
    render(){
        return(
            <div>No Room</div>
            )
    }
}

您可以在图像中看到,当没有名为 kat 的地方时,不会显示 No Room 文本 enter image description here

我做错了什么?

最佳答案

在根组件中,本地状态 (this.state.place) 是一个数组,用于定义是显示 Room 组件还是 NoRoom 组件。

如果你的API没有找到任何匹配的地方,那么this.state.place是一个空数组,即truthy 。这就是为什么你只需要在渲染方法中检查数组的长度:

if (this.state.place.length > 0) {

详细说明:

您的 UI 行为由组件状态定义。该状态的初始结构必须在您的组件中描述,这就是您在组件构造函数中所做的事情:

this.state = {place: []};

此初始状态将在组件的第一次渲染期间使用。

然后,每次您想要更新此状态时,您都可以使用属性“place”的新值调用 this.setState(),为了保持一致性,该值必须是一个数组。

在 render() 方法中,您只需根据状态的当前值描述您的 UI。因为“place”始终是一个数组,所以要检查其中是否有数据,唯一可以做的就是测试该数组的“length”属性(没有数据时,length === 0)。如果您只像最初那样检查数组本身(if (this.state.place) { ... }),它将始终评估为“true”(因为数组,即使是空的,也始终是“true”)并且这不是你想要的。

关于javascript - 如果没有用户查询的地名,我无法显示 noroom 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36396294/

相关文章:

javascript - JS 改变字符串格式

javascript - 将代码分配给特定按钮

ajax - 加载 cometd /服务器推送iframe时,停止浏览器 “throbber of doom”

javascript - 如何对 map 使用await(React)

javascript - reactjs axios 获取带有自定义 header 的请求

javascript - 使用 jQuery 和 Javascript 更改 DIV 内容的功能不起作用

javascript - Vue 实异常(exception)部的“vm”对象并在方法内部调用 Mounted undefined

javascript - 如何使用 ajax.get 调用从 node.js 服务器获取响应

javascript - 在 html 输入字段中加载 ajax 值

javascript - 调试 React 上下文重新渲染