简体   繁体   中英

React TypeError: Cannot read property 'includes' of undefined

This is a demo of data that is read from the firebase database,

without the.includes('') , it works very fine, but i want it to only show data that is typed in a textField

  • I only posted the important part, StackOverflow will not approve my question if it has too many codes*
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>

it keeps showing me the error above, what could be wrong, Please, is there another workaround?

To answer your subsequent question about using filter, instead of map with display set to none.

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>

On my phone so not tested.

Edit: Now also filters out array entries which do not have a name property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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