在 React 16 和 Bootstrap 4 中,如何将 bootstrap 选项卡组件中的每个选项卡映射到 URL?

In React 16 and Bootstrap 4, how do I map each tab in bootstrap Tabs component to a URL?

我正在使用 Bootstrap 构建 React 16.13.0 应用程序 4. 我想在特定组件上使用 Tabs,src/components/Edit.jsx ...

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { Tabs, Tab } from "react-bootstrap";

import FormContainer from "../containers/FormContainer";
import ListPeople from "../components/people/ListPeople";
import { DEFAULT_COUNTRY_CODE } from "../utils/constants";

const { REACT_APP_PROXY } = process.env;

const Edit = (props) => {
  const { id } = useParams();
  const [key, setKey] = useState("home");
  const [coop, setCoop] = useState(null);

  useEffect(() => {
    if (coop == null) {
      fetch(REACT_APP_PROXY + "/coops/" + id)
        .then((response) => {
          return response.json();
        })
        .then((data) => {
          const coop = data;
          coop.addresses.map((address) => {
            address.country = { code: address.locality.state.country.code };
          });
          console.log("edit cop ...");
          console.log(coop);
          setCoop(data);
        });
    }
  }, [props]);

  if (coop == null) {
    return <></>;
  }
  return (
    <div className="container">
      <h1>{coop.name}</h1>

      <Tabs id="controlled-tabs" activeKey={key} onSelect={(k) => setKey(k)}>
        <Tab eventKey="home" title="Home">
          <FormContainer coop={coop} />
        </Tab>
        <Tab eventKey="people" title="People">
          <ListPeople coop={coop} />
        </Tab>
      </Tabs>
    </div>
  );
};

export default Edit;

我还没有弄清楚该怎么做的是如何将每个选项卡映射到 URL?现在我有“主页”和“人物”标签。我想将“主页”选项卡映射到“/edit/

使用 react-router 非常简单:

import {Route} from 'react-router-dom';

const Edit = () => {
  const { id } = useParams();
  ...
  return (
    <Route path="/edit/:id/:tab">
      {({ match, history }) => {
        const { tab } = match ? match.params : {};

        return (
          <Tabs
            activeKey={tab}
            onSelect={(nextTab) => history.replace(`/edit/${id}/${nextTab}`)}
          >
            ...
          </Tabs>
        );
      }}
    </Route>
  );
};

这是一个example

或者,如果您的父路由路径看起来像 /edit/:id/:tab 那么,您可以:

const Edit = () => {
  const { id, tab } = useParams();
  const history = useHistory();
  ...
  return (
    <Tabs activeKey={tab} onSelect={(nextTab) => history.replace(`/edit/${id}/${nextTab}`)}>
    // or if you wish, you can use history.push instead of history.replace
      ...
    </Tabs>
  );
};