【问题标题】:How to fetch an array of objects and render it in the component as a normal text using React Hooks?如何使用 React Hooks 获取对象数组并在组件中将其呈现为普通文本?
【发布时间】:2021-07-09 12:04:37
【问题描述】:

我想在从 API 获取数据的应用中显示一些卡片信息。每个客户有 1、2 或 3 张不同的卡,我使用 JWToken 进行身份验证,但我没有在此处包含它。因此,API 响应不是静态的。

Request: GET "/xx/cards"

Response is an array of objects: 

[
    {
        "cardId": "1",
        "cardType": {
            "3": "General Card" 
        },
        "salutation": {
            "1": "Mrs." 
        },
        "firstName": "Test",
        "lastName": "User",
        "status": 'active',
        "creationDate": "30.10.2020",
        
    },
   {
        "cardId": "2",
        "cardType": {
            "2": "Special Card" 
        },
        "salutation": {
            "2": "Mr." 
        },
        "firstName": "Test1",
        "lastName": "User1",
        "status": 'active',
        "creationDate": "30.10.2020",
        
    },
 
]

在 React 上下文中:

const [cards, setCards] = useState<any>([]);

在 MyCards.tsx 组件中:

const MyCards: React.FC = () => {
  const {
    cards,
    setCards,
  } = React.useContext(AuthContext);

  
  const [content, setContent] = useState([]);

  useEffect(() => {
    axios.get("/xx/cards").then(
      (response) => {

        setContent(response.data);
        setCards(response.data);  
      },
      (error) => {
        const _content =
          (error.response && error.response.data) ||
          error.message ||
          error.toString();

        setContent(_content);
      }
    );
  }, []);

  return (
    <React.Fragment>
      <IonPage className="ion-page" id="main-content">
       
       <IonContent className="ion-padding">
          <h1>Your Cards</h1>

          <p>{JSON.stringify(cards)}</p>

        ...HERE I should write some code but don't know what...

        </IonContent>
      </IonPage>
    </React.Fragment>
  );
};

export default MyCards;

我想在我的组件中将卡片列为普通文本(如下所示):

Mrs. Test User
Card Id: 1
Card Type: General Card

Mr. Test1 User1
Card Id: 2
Card Type: Special Card

如何做到这一点?我真的不知道如何为对象数组设置状态。 任何帮助,将不胜感激。谢谢:)

【问题讨论】:

  • 我认为您需要映射数据。看看pluralsight.com/guides/…。它将类似于 {cards && data.map((x) => (

    {x.firstname}

    ))}。

标签: javascript arrays reactjs typescript ionic-framework


【解决方案1】:

解决方案是在您的数组see here 上使用 map 函数

return(
   ...
    {
     cards.map(card => (
        <p>
          {card.firstName} {card.lastname}<br/>
          Card Id: {card.cardId}<br/>
          ...
        </p>
     ))
    }
   ...
)

像这样,但对我来说,api 中存在一个问题,即对象中的所有键号..

迭代的更好选择是这样的对象数组:

  [
   {
    "cardId": "1",
    "cardType": "General Card",
    "salutation": "Mrs.",
    "firstName": "Test",
    "lastName": "User",
    "status": 'active',
    "creationDate": "30.10.2020",
   },
   ...

  ]

【讨论】:

  • 非常感谢,它成功了。关于 Salutation 或 Card Type 中的键号,我使用 Object.values 来获取值:

    Card type: {Object.values(card.cardType)}

  • 不错!欢迎您查看数组的所有不同功能,例如 filter()、reducer()、sort()..etc
【解决方案2】:

我认为您正在寻找的是通过对象数组进行映射并仅显示它们,如下所示:

...

<p>{JSON.stringify(cards)}</p>

{cards?.map(card => (
  <div>
    <p>{Object.values(card.salutation)[0] card.firstName card.lastName}</p>
    <p>Card Id: {card.cardId}</p>
    <p>Card type: {Object.values(card.cardType)[0]}</p>
  </div>
))}

...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    相关资源
    最近更新 更多