簡體   English   中英

我在 React 組件上進行了一個 API 調用,從中獲取數據並將其傳遞給一個狀態。 我也想在另一個組件上使用相同的數據

[英]I made an API call fetching data from it on a React component and passed it on to a state. I want to use the same data on another component too

正如標題所說,我從組件的 API 中獲取了數據。 我希望該組件就像獲取數據的“存儲”一樣,同時將這些數據呈現到另一個組件上。 如果可能,我該怎么做?

這是Fetch.js這是應該從API獲取數據,並存儲在personstate 現在,我想打破存儲在對象person ,並分成不同的varfnamelname ,等等。

import React from "react";
export default class Fetch extends React.Component {
state = {
loading: true,
person: null,
 };

async componentDidMount() {
console.log("mounted");

const url = "https://api.randomuser.me/";
const response = await fetch(url);
const data = await response.json();
this.setState({
  loading: null,
  person: data.results[0],
});
}

render() {
return console.log(this.state.fname);
 }
}

現在上面說的一切都完成了,我有另一個文件Main.js ,我想在其中顯示從Fetch.js獲取的數據(分解為每個變量,如 fname,lname)。

import React from "react";
export default class Main extends React.Component {
render() {
return (
  <div>
    {this.state.loading || !this.state.person ? (
      <div>Loading</div>
    ) : (
      <div>
        Name: {this.state.fname} {this.state.lname}
      </div>
    )}
  </div>
       );
      }
     }

您可以將屬性中的數據從父組件傳遞給子組件:

function ParentComponent() {
  const data = fetch(...);

  return <ChildComponent data={data} />
}
...
function ChildComponent(props) {
  const data = props.data;

  ...
}

但是,如果您可能需要在許多組件中使用這些數據(或者子組件有一堆層),那么為此目的使用 React 的 Context 會更方便: https : //uk.reactjs.org/docs/context .html

暫無
暫無

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

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