首页 文章

React,Divs里面的三元条件都没有渲染

提问于
浏览
1

在我的一个反应组件中有一个名为“buildRow()”的方法,它循环遍历对象列表并使用相应的数据呈现div . 例如,如果列表中有600个对象,并且我使用map循环遍历它,则所有div将在页面上呈现,并具有自己的 Headers 等 .

例如,下面的代码在我的页面上渲染大约600个div,每个div都有自己的相应数据 .

buildRow() {
     return (
   this.state.posts.map(events =>
       <div key={events.key} className='result_box'
              onClick={ () => this.click(events.name, events.description, 
              events.time)} id={events._id}>

               <p>{events.name}</p>
               {events._id}
               {events.place && events.place.location && <p>
               {events.place.location.city}</p>}
       </div>
   )
  )};

现在,我想实现一个搜索过滤功能 . 我只想返回具有特定数据参数的div . 例如,如果我在搜索框中键入“Austin”,则只会呈现其位置数据为“Austin”的div . 代码如下:

buildRow() {
    return (
    this.state.posts.map(events =>
      {events.place &&
        events.place.location &&
        this.props.searchVal === events.place.location.city ?
           <div key={events.key} className='result_box'
              onClick={ () => this.click(events.name, events.description, 
              events.time)}
              id={events._id}>

             <p>{events.name}</p>
             {events._id}
             {events.place && events.place.location && <p>
             {events.place.location.city}</p>}
           </div>
         : console.log(this.props.searchVal)
      }
    ) 
  )
}

我想要做的是过滤并只使用三元运算符渲染与搜索条件匹配的div . 但是,这不会渲染div . 然而有趣的是,三元操作按预期工作 . 例如,如果我输入“Austin”并且“Austin”有5个匹配的结果,并且假设我们有600个对象,则console.log只会达到595次 . 我甚至测试了我在console.log里面的成功条件,那些日志显示!似乎在渲染div时,它没有发生 . 谁能帮我吗?

1 回答

  • 4

    看起来 Map 回调实际上并没有返回一个值(因为表达式已被放入大括号) . 你可能想做这样的事情:

    buildRow() {
        return this.state.posts
            .filter(events => 
                events.place 
                && events.place.location
                && events.place.location.city === this.props.searchVal)
            .map(events => 
                <div key={events.key} className='result_box'
                    onClick={() => this.click(events.name, events.description, 
                    events.time)}
                    id={events._id}>
    
                    <p>{events.name}</p>
                    {events._id}
                    <p>{events.place.location.city}</p>
                </div>);
    }
    

相关问题