首页 > 解决方案 > React TypeError:无法读取未定义的属性“包含”

问题描述

这是从 firebase 数据库中读取的数据的演示,

没有 .includes('')它工作得很好,但我希望它只显示在 textField 中输入的数据

const arr = [
  { age: 1, name: 'Raphael' },
  { age: 3, name: 'Inyang' },
  { age: 6, name: 'Ifiok' },
  { age: 8, name: 'Ekpedeme' },
];

<ul style={{ listStyleType: 'none' }}>
  {arr.map(function (item) {
    return (
      <li>
        <div
          style={{
           
            justifyContent: 'flex-start',
            width: 'auto',
            fontSize: 'calc(4px + 2vmin)',
            display: item.name.includes('Raphael') ? 'flex : 'none',
            justifyContent: 'flex-start',
          }}>
          <p>
            {item.name}: {item.age}
          </p>
        </div>
      </li>
    );
  })}
</ul>

它一直向我显示上述错误,可能是什么问题,请问 还有其他解决方法吗?

标签: javascriptarraysreactjsreact-nativeweb

解决方案


要回答有关使用过滤器的后续问题,而不是显示设置为无的地图。

const arr = [
  { age: 1, name: 'Raphael' },
  { age: 3, name: 'Inyang' },
  { age: 6, name: 'Ifiok' },
  { age: 8 },
];

const filtered = arr.filter(
  item => item.hasOwnProperty('name') && item.name.includes('Raphael')
);

<ul style={{ listStyleType: 'none' }}>
  {filtered.map(function (item) {
    return (
      <li>
        <div
          style={{
            justifyContent: 'flex-start',
            width: 'auto',
            fontSize: 'calc(4px + 2vmin)',
            display: 'flex',
            justifyContent: 'flex-start',
          }}>
          <p>
            {item.name}: {item.age}
          </p>
        </div>
      </li>
    );
  })}
</ul>

在我的手机上,所以没有测试。

编辑:现在还过滤掉没有名称属性的数组条目


推荐阅读