【发布时间】:2021-11-07 07:28:20
【问题描述】:
所以,我有一个看起来像这样的 sidenav 组件:
<MenuItems>
<NavLink to="/contacts/new">New</NavLink>
<NavLink to="/contacts/list">New (all)</NavLink>
<NavLink to="/contacts/archived">Archived</NavLink>
<NavLink to={`/contacts/responsible/${user?.id}`}>{user?.name}</NavLink>
</MenuItems>
所有这些链接都重定向到我的主页,如您在此处看到的:
<BrowserRouter>
<Switch>
<Route path={[
'/contacts/new',
'/contacts/list',
'/contacts/archived',
'/contacts/responsible/:responsible',
'/contacts/category/:category',
]}>
<Home />
</Route>
</Switch>
</BrowserRouter>
问题是,在我的<Home /> 页面中,我有一个<Contacts /> 组件,这是我访问上述任一路由时唯一应该更新的组件。基本上它应该根据当前路由更新一个调用不同 api 端点的列表。例如:如果当前的react路由是/contacts/archived,那么我需要调用的端点是http://example.com/api/archivedContacts。
为了清楚起见,我正在尝试做的一个例子是这样的:
<Route path="/contacts/new" endpoint="/newContacts">
<Home />
</Route>
<Route path="/contacts/archived" endpoint="/archivedContacts">
<Home />
</Route>
<Route path="/contacts/category/:id" endpoint="/categoryContacts/:id">
<Home />
</Route>
然后在 <Home /> 内部的 <Contacts /> 组件中,我想做类似的事情:
export function Contacts() {
// get the endpoint from the route or something like that
const { pathname, endpoint } = useLocation();
// useContacts is my context responsible to fetching and returning my contacts
const { isLoading, fetchContacts, contacts } = useContacts();
// refetch the contacts whenever the endpoint changes
useEffect(() => {
fetchContacts(endpoint);
}, [endpoint, fetchContacts]);
return (
<>
<Container>
{isLoading && (
<Loading>
<LoadingSpinner size={25} thickness={2} />
</Loading>
)}
<Table>
<thead>
<tr>
<th>Contact</th>
<th>Last seen</th>
<th>Responsible</th>
<th>Category</th>
</tr>
</thead>
<tbody>
{// render contact list based on the route}
{!isLoading && contacts.map((contact) => {
{// list}
})}
</tbody>
</Table>
</Container>
</>
);
}
感谢您的帮助!
【问题讨论】:
标签: javascript reactjs routes react-router