繁体   English   中英

在Reactjs中的render方法外部映射prop数据

[英]Map prop data outside render method in Reactjs

我想在函数中的render方法外部映射数据,并在render中返回它。 但是我遇到映射错误,我不确定原因。

下面是应该将数据映射到render外部的函数:

filterItems = (itemList) => {
        let result = [];

        const { searchInput,alphabet } = this.state;
        if(searchInput || alphabet) {
          result = itemList.filter((element) => (element.name.charAt(0).toLowerCase() === alphabet.toLowerCase()) && 
          this.elementContainsSearchString(searchInput, element));
        } else {
          result = itemList;
        }    
        result = result.map((item)=> (<li>{item.name}<a href="#"><img src={item.image_url} className="img-responsive" /></a></li>))
        return result;
      }

在render方法中这样访问:

let celebrity = this.props.items.celebrity
const filteredList = this.filterItems(celebrity);
return (
        <div className="container no-padding">
            <div className="row celeb-grid">
                <ul className="no-padding celeb-items col-md-12">
                    {filteredList}

                </ul>
            </div>

        </div>
    );

注意:如果我执行console.log,我将获取数据:

console.log (celebrity);

错误截图:

截图

我的猜测是,您正在从端点(可能是在componentDidMount获取名人列表,但您是在加载数据之前渲染组件。 这意味着您要将undefined传递给filterItems方法,并且无论条件的结果如何,result都是undefined ,并且您无法map未定义的对象。

为了解决这个问题,您需要组件在加载数据之前显示列表以外的内容。

let { celebrity } = this.props.items;

if (!celebrity && !celebrity.length) return <div />

return (
  <div className="container no-padding">
    <div className="row celeb-grid">
      <ul className="no-padding celeb-items col-md-12">
        {this.filterItems(celebrity)}
      </ul>
    </div>
  </div>
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM