如何使用 React router dom v6 从 <Route /> 获取道具

How to get props from <Route /> with react router dom v6

当我单击 table 的一行时,我试图将 :id 传递给 url 尝试使用 navigate("/edit/"+props);onClick={() => handleClick(data.PacienteId)} 但它不起作用然后使用 useParams 并创建 handleProceed 将其用作 onclick={handleProceed} 但它仍然不起作用我只是得到 url 由 Apiurl 提供,但 /undefined

这是我的路线

function App() {
  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/" exact element={<Login  />} />
          <Route path="/dashboard" exact element={<Dashboard  />} />
          <Route path="/new" exact element={<Nuevo  />} />
          <Route path="/edit/:id" exact element={<Editar />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

这是我的仪表板,我想将 ID 传递给 url 单击 table

export const Dashboard = (props) => {
  const [paciente, setPaciente] = useState([]);
  const {id}=useParams();
  const navigate = useNavigate();
  useEffect(() => {
    let url = `${Apiurl}pacientes?page=1`;
    axios.get(url).then((response) => {
      setPaciente(response.data);
    });
  }, []);

  const handleClick = (props) => {
    /* navigate("/edit/" + props); */
    navigate(`/edit/${id}`);
  };
  const handleProceed = (e) => {
    /* history.push(`/edit/${id}`); */
    navigate(`/edit/${id}`);
  };
  return (
    <>
      <Header />
      <div className="container">
        <table className="table table-dark table-hover">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">DNI</th>
              <th scope="col">NOMBRE</th>
              <th scope="col">TELEFONO</th>
              <th scope="col">CORREO</th>
            </tr>
          </thead>
          <tbody>
            {paciente.map((data, i) => {
              return (
                <tr key={i} /* onClick={handleProceed} */onClick={() => handleClick(data.PacienteId)}>
                  <td>{data.PacienteId}</td>
                  <td>{data.DNI}</td>
                  <td>{data.Nombre}</td>
                  <td>{data.Telefono}</td>
                  <td>{data.Correo}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

尝试 <Route path="/dashboard/:id" element={<Dashboard />} /> 通过这种方式,您可以在组件 DashBoard

中获取 id

你是这个意思吗?

在您的 handle click 函数中,您将参数命名为 props,但您已尝试在 navigate 方法中使用“id”变量。在 navigate 方法中使用 props 或将参数名称更改为 id。

 const handleClick = (id) => {
   navigate(`/edit/${id}`);
 };

********* 或 ************

 const handleClick = (props) => {
   navigate(`/edit/${props}`);
 };