簡體   English   中英

Nextjs:在對象數組上使用 map 時無法呈現組件。 對象作為 React 子項無效

[英]Nextjs: Cant render a component while using map over a array of objects. Objects are not valid as a React child

我不知道為什么當我想在 map function 中呈現一個組件時,基本上我有一個列表組件,當我從 API 和 email 等中獲取數據時,我希望該組件呈現該信息。 但我收到以下錯誤:

Unhandled Runtime Error

Error: Objects are not valid as a React child (found: object with keys {email, phone, nick}). If you meant to render a collection of children, use an array instead.

我的列表組件如下所示:

import React from 'react'

export default function List(email, nick, phone) {
  return (
    <div align="center">
        <hr />
        <strong>Email: </strong> 
        <p>{email}</p>
        <strong>Nick: </strong> 
        <p>{nick}</p>
        <strong>Phone: </strong> 
        <p>{phone}</p>
    </div>
  )
}

我的列表用戶頁面如下所示:

import React from 'react'
import Nav from '../../components/Nav/Nav'
import { useEffect, useState } from 'react';
import List from '../../components/User/List';

export default function index() {
  const [users, setUsers] = useState([])

  const fetchUsers = async () => {
    const response = await fetch("http://localhost:3001/api/internal/users");
    const data = await response.json();
    console.log(data["data"])
    setUsers(data["data"])
  }

  useEffect(() => {
    fetchUsers()
  }, [])

  return (
    <div>
      <Nav />
        {users.map(user => (
            <List
              email={user.attributes.email}
              phone={user.attributes.phone}
              nick={user.attributes.nick} 
            />
        ))}
    </div>
    
  )
}

更新 21 ABR

出於某種原因,當我這樣做時:

export default function List(email, phone, nick) {
  return (
    <div align="center">
        <hr />
        <strong>Email: </strong> 
        <p>{email.email}</p>
        <strong>Nick: </strong> 
        <p>{email.phone}</p>
        <strong>Phone: </strong> 
        <p>{email.nick}</p>
    </div>
  )
}

它有效......有人知道它可以是什么嗎?

你以錯誤的方式傳遞道具。 要么將它用作道具中的單個 object,要么使用解構方法將所有道具放在 {} 中。

export default function List({email, phone, nick}) {}


         OR

export default function List(props) {
  return (
   <div align="center">
    <hr />
    <strong>Email: </strong> 
    <p>{props.email}</p>
    <strong>Nick: </strong> 
    <p>{props.phone}</p>
    <strong>Phone: </strong> 
    <p>{props.nick}</p>
</div>

) }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM