【问题标题】:Is it possible to set a variable based on the current route?是否可以根据当前路线设置变量?
【发布时间】: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>

问题是,在我的&lt;Home /&gt; 页面中,我有一个&lt;Contacts /&gt; 组件,这是我访问上述任一路由时唯一应该更新的组件。基本上它应该根据当前路由更新一个调用不同 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>

然后在 &lt;Home /&gt; 内部的 &lt;Contacts /&gt; 组件中,我想做类似的事情:

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


    【解决方案1】:

    你可以这样做:

    import { useLocation } from 'react-router-dom'
    
    export function Contacts() {
      const { pathname } = useLocation();
    
      useEffect(() => {
        if (pathname.includes('something')) {
          fetch('URL1')
        } else if (pathname.includes('anotherPath')) {
          fetch('URL2')
        }
      }, [pathname, fetchContacts]);
      
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多