簡體   English   中英

你如何渲染數組中獲取的數據?

[英]How do you render the fetched data in the array?

我想從url中讀取json數據,放入一個空數組,放入一個react組件,打印出來。 但是,如果將 json 數據放在結果數組中,並將 output 放在 console.log 中,則只有空數組是 output。 推陣有錯嗎?

另外,我想將這個 url 重復 100 次,然后按多個計數的順序打印出來。 例如,計數:15 {Json 內容}。 謝謝你。

讓結果 = [];

fetch("http:// ~ ").then(res => { return res.json()}).then(data => result.push(data)).then(()=>console.log(result ));

最后一個.then是多余的。 console.log(result)放在與result.push(data)相同的 function 中,它應該可以工作。 不過,您確實需要在 function 中添加括號,因為它將不再是“單線”。

fetch("http:// ~ ")
  .then(res => res.json())
  .then(data => {
    result.push(data);
    console.log(result);
  });

您需要使用 useEffect 和/或 useState 掛鈎來觸發重新渲染。

let result = [];

useEffect(()=>{
fetch("http:// ~ ")
  .then(res => res.json())
  .then(data => {
    result.push(data);
    console.log(result);
  });
},[])

不是這會在您獲取數據后觸發重新渲染

嘗試這個,

import { useState, useEffect } from "react";

export default function App() {

  const [state, setState] = useState([])

  useEffect(() => { 
      fetch("http:// ~ ")
        .then(res => res.json())
        .then(data => setState([...state, data]));
  }, [])

  return (
    <div className="App">{JSON.stringify(state)}</div>
  );
}

暫無
暫無

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

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