我正在尋找一種將變數 (backend_url={backend_url}) 傳遞給 React 中的多個組件的簡單方法。我目前使用的方式看起來非常重復。
<Routes>
<Route exact path="/posts/:username/newPost" element={<CreatePost backend_url={backend_url}/>} />
<Route exact path="/posts" element={<PostList backend_url={backend_url}/>} />
<Route exact path="/posts/:id/" element={<PostDetail backend_url={backend_url}/>} />
<Route exact path="/posts/:id/delete" element={<DeletePost backend_url={backend_url}/>} />
<Route exact path="/posts/:id/update" element={<UpdatePost backend_url={backend_url}/>} />
<Route exact path="/myPosts" element={<MyPosts />} />
</Routes>
您對更簡單方法的建議將不勝感激。
謝謝你。
uj5u.com熱心網友回復:
你可以使用 React Context 系統來傳遞backend_urlprop。
內部backendUrlContext.js檔案
import {createContext, useContext} from "react";
const defaultBackendUrlValue = "";
const backendUrlContext = createContext(defaultBackendUrlValue);
export const BackendUrlProvider = backendUrlContext.Provider;
export const BackendUrlConsumer = backendUrlContext.Consumer;
export const useBackendUrl = () => useContext(backendUrlContext);
內部路由檔案
import {BackendUrlProvider} from "backendUrlContext";
<BackendUrlProvider value={backend_url}>
<Routes>
<Route exact path="/posts/:username/newPost" element={<CreatePost />} />
<Route exact path="/posts" element={<PostList />} />
<Route exact path="/posts/:id/" element={<PostDetail />} />
<Route exact path="/posts/:id/delete" element={<DeletePost />} />
<Route exact path="/posts/:id/update" element={<UpdatePost />} />
<Route exact path="/myPosts" element={<MyPosts />} />
</Routes>
</BackendUrlProvider>
BackendUrlProvider然后您可以使用useBackendUrl鉤子訪問嵌套在其中的任何路由元素內的 backend_url 值
import {useBackendUrl} from "backendUrlContext";
function CreatePost() {
const backendUrl = useBackendUrl();
/*
...rest of the logic
*/
}
而且這種方法也適用于不是直接嵌套路由的任何嵌套子組件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/425846.html
上一篇:Anylogic:為什么我的帶有代理變數值條件的SelectOutput不起作用?[復制]
下一篇:變數的生命周期
