【问题标题】:React : Hide "params" from url with React-routerReact:使用 React-router 从 url 中隐藏“参数”
【发布时间】:2021-05-05 10:00:32
【问题描述】:

我有一个从 url 接收自定义 id 并根据该 id 获取数据的页面。

例如:

let params = useParams();
useEffect(() => {
    axios
        .get("http://localhost:8000/api/profile/" + params.id)
        .then((response) => {
            setUsername(response.data.username);
        })
        .catch((err) => console.log(err));
}, []);

问题是参数显示在url中,我想隐藏它,怎么做?

输出的现有路由例如http://localhost:8000/customize/9:

  <Route path="/customize/:id" component={Home} />

我想在网址中包含什么:

http://localhost:8000/customize/

【问题讨论】:

  • 如果你不希望参数出现在 URL 中,为什么要把它放在路由中?像这样从路径中删除它path="/customize" no ?
  • @Marc Charpentier 我想将 id 传递给页面,以便可以根据该 id 加载元素。如果有其他选择,我会欢迎的。
  • 在下面查看我的答案

标签: reactjs react-router react-router-dom


【解决方案1】:

也许你可以试试这个:

获取数据后使用 useHistory() 和 history.push() 隐藏 URL 中的参数

import { useHistory, useParams } from "react-router-dom";

let params = useParams();
let history = useHistory();
useEffect(() => {
    axios
        .get("http://localhost:8000/api/profile/" + params.id)
        .then((response) => {
            setUsername(response.data.username);
            history.push("/customize");
        })
        .catch((err) => console.log(err));
}, []);

这里在:id 之后添加一个? 来指定这是一个可选参数,可以存在或不存在

<Route path="/customize/:id?" component={Home} />

【讨论】:

  • 很好,不幸的是,在正确获取数据之前,您的 id 仍会在 url 中
【解决方案2】:

如果您不需要这种方式,您可以从路由参数中删除 id。然后以不同的方式将 id 传递给组件,例如作为组件的道具。

<Route path="/customize" render={() => <Home id={9} />} />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-26
    • 2015-03-12
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    相关资源
    最近更新 更多