簡體   English   中英

在 react.js 中正確映射 API 響應

[英]Correctly Map API response in react.js

我已經能夠制作 api 並在控制台上確認響應。 我還能夠從響應中過濾掉所需的有價值的元素。

  1. 我目前的問題是將值映射到相應的 html 元素中。 請看我的代碼。 我正在使用 react 和 Next.js

  2. 也有人可以幫助我,說我想使用此方法映射多個響應props.entry?.map((enties, i) => ()什么是最佳實踐。

非常感謝,我是 javascript 的大新手。

import React, { Component } from "react"
import { Octokit } from "@octokit/core"

const token = "***********************4571B*";
const id = "***********************e911c*";
// Octokit.js
// https://github.com/octokit/core.js#readme

class Dairy extends Component{
    constructor(props){
        super(props);
        this.state = {
          entry: [],
        }
      }
      async componentDidMount()  {
      const octokit = new Octokit({
        auth: token
      })
      
       const response = await octokit.request('GET /gists/{gist_id}', {
        headers: {
            accept: 'application/vnd.github.v3+json',
          },
        gist_id: id,
        
      })
      console.log(response);
      //Below are the values i need from the response
      console.log(response.data.description);
      console.log(response.data.files.ahmed.content);
      console.log(response.data.created_at);

      this.setState({entry: [response.data]})

    }
  render(){
          //here's where i want to map the values.
    return(
       <div>
         
           <div class="rounded-lg border border-stone-800 text-stone-100 bg-opacity-20 bg-stone-800 p-8">
               <h3 class="font-am text-2xl mb-5">{entry.data.description}</h3><div class="space-y-10"><a href="https://www.goodreads.com/book/show/13589182-mastery" target="_blank" rel="noopener noreferrer" class="content-card block hover:cursor-pointer text-stone-300 hover:text-stone-400 group">
               <div class="flex justify-between items-center"><div class="text-lg font-medium mb-1 text-stone-100 group-hover:text-stone-400 transition-colors duration-300">{entry.data.files.ahmed.content}</div>
               <div class="font-fanwood italic text-lg text-stone-400 group-hover:text-stone-500 transition-colors duration-300">{entry.data.created_at}</div></div>
               <div class="text-sm text-stone-400 group-hover:text-stone-500 transition-colors duration-300">written by Robert Greene</div></a></div></div> 
       </div>
    )}
}

export default Dairy;

您有使用.map呈現項目列表的正確想法,但您還需要確保在執行此操作時, .map函數中的每個返回項目都有一個關鍵屬性,該屬性在父節點。

如果你從 api 調用數據,這通常會在入口對象中作為 _id、id 或 uuid 等。

除此之外,如何呈現此列表取決於響應數據中每個條目的數據結構。

以下是一個示例,如果 response.data 是一個采用這種形式的條目數組{id: uuid, text: string}

   render(){
          //here's where i want to map the values.
    return(
       <div>
         {this.props.state?.map((entry, idx)=>{
            return <div key={entry.id}>{entry.text}</div>
         })}
       </div>
    )}
}

暫無
暫無

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

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