Фильтр карты в React. Объекты недопустимы как дочерние элементы React. Если вы хотите отобразить коллекцию дочерних элементов, используйте вместо этого массив - PullRequest
0 голосов
/ 20 января 2020
function Main(){
    // create an array that holds objects
    const people = [
        {
            firstName: 'Fathi',
            lastName: 'Noor',
            age: 27,
            colors: ['red', 'blue'],
            bodyAttributes: {
                weight: 64,
                height: 171
            }
        },
        {
            firstName: 'Hanafi',
            lastName: 'Noor',
            age: 26,
            colors: ['white', 'black'],
            bodyAttributes: {
                weight: 62,
                height: 172
            }
        }
    ]

    return(
        <main>
            <div>
                /* display person age equal to 27 using filter using ES6 arrow */
                {people.filter(person => person.age == 27)}
            </div>
        </main>
    )
}

Я очень плохо знаком с , реагирую и использую map вместо обычной функции l oop.

Когда я запускаю этот код, он дает мне эту ошибку (как показано ниже)

map filter error

Можете ли вы, ребята, научить меня правильному пути о том, как отобразить все данные человека, когда отфильтрованы по возрасту равно 27?

Ответы [ 3 ]

2 голосов
/ 20 января 2020

Вы пытаетесь вернуть объект, и это невозможно.


function Main(){
    // create an array that holds objects
    const people = [
        {
            firstName: 'Fathi',
            lastName: 'Noor',
            age: 27,
            colors: ['red', 'blue'],
            bodyAttributes: {
                weight: 64,
                height: 171
            }
        },
        {
            firstName: 'Hanafi',
            lastName: 'Noor',
            age: 26,
            colors: ['white', 'black'],
            bodyAttributes: {
                weight: 62,
                height: 172
            }
        }
    ]

    const filterdPeople = people.filter(person => person.age == 27)

    return(
        <main>
            <div>
                {filterdPeople.map(person => {
                  return (
                    <div key={person.lastName}>
                      <p>First name: {person.firstName}</p>
                      <p>Last name: {person.lastName}</p>
                      <p>Age: {person.age}</p>
                      <p>Colors: {person.colors.map(color => (<span>{`${color}, `}</span>))}</p>
                     <p>
                      <span>Body Attributes: </span>
                      <span>Weight: {person.bodyAttributes.weight}</span>
                      <span>Height: {person.bodyAttributes.height}</span>
                     </p>
                   </div>
                  )
                })}
            </div>
        </main>
    )
}
1 голос
/ 20 января 2020
function Main(){
    // create an array that holds objects
    const people = [
        {
            firstName: 'Fathi',
            lastName: 'Noor',
            age: 27,
            colors: ['red', 'blue'],
            bodyAttributes: {
                weight: 64,
                height: 171
            }
        },
        {
            firstName: 'Hanafi',
            lastName: 'Noor',
            age: 26,
            colors: ['white', 'black'],
            bodyAttributes: {
                weight: 62,
                height: 172
            }
        }
    ]

    return(
        <main>
            <div>
                /* display person age equal to 27 using filter using ES6 arrow */
                <table>
                <tr>
                <th>firstName</th>
                <th>lastName</th>
                <th>age</th>
                <th>colors</th>
                <th>bodyAttributes<th>
                </tr>
                {people.filter(person => person.age == 27).map(item=>{
                    return(
                        <tr>
                           <td>{item.firstName}</td>
                           <td>{item.lastName}</td>
                           <td>{item.age}</td>
                           <td>
                           <ul>
                             {
                                 item.colors.map(color=>{
                                     return <li>{color}</li>
                                 })
                             }
                           </ul>
                           {}
                           </td>
                           <td>
                           <ul>
                             <li>W:{item.bodyAttributes.weight}</li>
                             <li>H:{item.bodyAttributes.height}</li>
                           </ul>
                           </td>
                        </tr>
                    )
                })}
              </table>
            </div>
        </main>
    )
}
1 голос
/ 20 января 2020

Вы должны map массив. См. Это do c.

Для каждого человека вы сами решаете, как отображать каждое поле, здесь я использовал <p> теги, вы можете отображать их в таблице или в Пользовательская карта .. Ваш выбор!

Помните, что внутри {} скобок идет Javascript выражений, а в () идет JSX, очень похоже на теги HTML, как вы можете видеть!

Прочитайте документы, следуйте инструкциям, это очень поможет!

{people.filter(person => person.age == 27).map(person => { return(
    <div>
      <p>First name: {person.firstName}</p>
      <p>Last name: {person.lastName}</p>
      <p>Age: {person.age}</p>
      <p>Colors: {person.colors.map(color => (<span>{color+" "}</span>)}</p>
      <p>
        <span>Body Attributes: </span>
        <span>Weight: {person.bodyAttributes.weight}</span>
        <span>Height: {person.bodyAttributes.height}</span>
      </p>
    </div>
)})}

...