![](/img/trans.png)
[英]Passing props from Container with fetch to one element via Link
[英]Passing Props from a fetch
假設我的 app.js 帶有一個 NavBar 組件,該組件具有指向每個頁面路徑的鏈接。
function App() {
return (
<div className="App">
<Router history={history}>
<header>
<NavBar />
</header>
<div>
<Switch>
<Route path="/" exact component={Home}/>
<Route path="/profile" component={Profile} />
<Route path="/contacts" component={Contacts} />
</Switch>
</div>
</Router>
</div>
);
}
export default App;
我的 home 組件將執行 fetch 以獲取我需要的 Home、Contacts & Profile 組件的詳細信息,如下所示:
import React, { useEffect, useState } from "react";
function Home() {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState([]);
useEffect(() => {
async function getView() {
setIsLoading(true);
const response = await fetch("https://personalapi.amazonaws.com/default/getview", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
data: {
data: "ti"
}
});
setData(data);
setIsLoading(false);
}
getView();
// eslint-disable-next-line
},[]);
return (
isLoading ? <div> Loading...</div> :
<div>
// put some of the data object here.
</div>
);
};
export default Home;
我如何將數據對象的其他部分傳遞給我的其他組件(聯系人、個人資料)。 我是 React 路由器的新手,所以我不確定它是如何工作的,但我掌握了 React Hooks 的竅門。 對此的任何指導或方向將不勝感激!
您的想法是正確的,但基本上,我認為只需將您的提取提升到應用程序級別。 假設這是您希望在應用程序的整個生命周期中保留的數據,請在 App.js 中調用它,並根據需要將信息通過 props 傳遞給每個子組件。
或者,如果這是一個過於簡單的示例,但您計划在許多不一定嵌套在 App.js 中的組件之間共享它,您可能需要研究狀態管理框架。 一些示例可能是 redux 或 mobx。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.