![](/img/trans.png)
[英]What's the proper way to pass dependencies between components in React?
[英]What is the proper way to pass parameters between urls using react router?
隨着 React Router v5.1 添加了 useParams、useHistory 和 useLocation,以及 react-hooks 和功能組件帶來的更改編碼約定,試圖找出使用現代版本 react-router 的預期方法變得令人困惑。
在使用 react router 編程導航時,如何在不同的 url 之間正確傳遞參數?
例如,假設我有一個名為component_a的組件,單擊該組件時會調用以下內容:
history.push("/home"); //history is defined as the return value of useHistory() from react-router-dom
我將某些component_a的屬性傳遞給另一個名為component_b的組件的正確方法是什么? Component_b 呈現如下:
<Route path="/home" component={component_b}/>
我知道 history.push() 需要第二個參數[state]
。 但是我在文檔中沒有看到任何示例。 我也找不到它的描述。
我也知道 useParams(),但是如果有太多變量無法通過 url 本身怎么辦?
鈎子在那里,所以你不必再使用 HOC withRouter
來從路由器獲取你需要的東西。
通過 URL 您應該只傳遞本機屬於 URL 的數據(例如路線名稱、ID、搜索參數等)
使用 state 理論上你可以傳遞你想要的任何東西,但實際上你可能會傳遞一些較小的數據塊(例如標志,ID)
使用路由器 v5,還有一種構建 Route 的新方法
<Route path="/home">
<YourComponent prop1 prop2 />
</Route>
在那里你定義了你所有的組件道具
對於其他一切,您應該使用應用商店,例如 Redux、MobX 或 Context,您將在history.push("/home");
並在您進入<YourComponent />
后訪問它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.