簡體   English   中英

React:為什么我不能將數據從一個功能組件傳遞到另一個功能組件?

[英]React: Why can't I pass data from one functional component to another functional component?

我有點不明白為什么我不能在兩個功能組件之間傳遞獲取的數據。 我嘗試使用 Hooks 並返回一條錯誤消息,建議將數組用於 object[Promise]。 知道我在這里錯過了什么嗎? 我對 React 還很陌生。 任何幫助,將不勝感激!

// Component A
function App() {
  const apiURL = "https://services9.arcgis.com/M4Su6cnNT6vqupbh/arcgis/rest/services/COVID19_Data/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json";
  const apiData = fetch(apiURL)
                    .catch(err=>console.log(err))
                    .then(data=>console.log(data));
  return (
    <div>
      <h1>Hello</h1>
      <DataVisualize data={apiData}/>
    </div>
  );
}

// Component B
function DataVisualize(props){
    return <div>{props.data}</div>;
}

您的apiData不包含您想要的實際數據 - 它只是一個 Promise。 它的catch也是在錯誤的地方(放.catch.then S),你需要調用.json.text的響應(通過決心返回值fetch按順序)獲得承諾解析到您需要的實際數據。

在檢索最終數據時設置一些狀態:

// Component A
function App() {
  const apiURL = "https://services9.arcgis.com/M4Su6cnNT6vqupbh/arcgis/rest/services/COVID19_Data/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json";
  const [data, setData] = useState();
  useEffect(
    () => {
      fetch(apiURL)
        .then(res => res.json())
        .then(setData)
        .catch(console.error); // handle errors
    },
    [] // run this only once, on mount
  );
  return (
    <div>
      <h1>Hello</h1>
      { data && <DataVisualize data={data}/> }
    </div>
  );
}

// Component B
function DataVisualize(props){
    return <div>{props.objectIdFieldName}</div>;
}

另請注意,結果似乎沒有任何.data屬性(盡管它確實有一個objectIdFieldName屬性,所以我將其作為示例)。

暫無
暫無

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

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