首页 > 解决方案 > 在位置更改 ReactJs 上保持参数一致

问题描述

我正在使用反应路由器 v4 来更改 ReactJs 中的位置。

this.props.history.push("/profile");

<Link to="/profile" />

上面的代码工作正常。

http://localhost:3000?source=test现在我想通过使用与上面相同的代码来保持 URL 中的参数一致。

一种方法是我在代码中找到所有出现的地方并添加条件,如果参数source=test存在,那么也将其附加到 URL 中,但这种方法对我来说看起来不太好,因为我在 every 上添加了条件redirectLink并且history.push

我发现的第二种方法是在反应路由器给出的位置更新上使用侦听器

在我的主要路线文件中

class App extends Component {

  componentDidMount() {
     this.unlisten = this.props.history.listen((location, action) => {
      if (/source=ep/.test(this.props.location.search)) {
        location.search = _startsWith(location.search, "?") ? location.search + "&source=test" : "?source=test"
      }
    });
  }
}

使用这种方法,我可以轻松地将参数附加到反应路由器的搜索查询中,但参数不会显示在 URL 中。

URL 看起来像这样http://localhost:3000/profile,当我从 react-router 获取搜索参数时,console.log(this.props.location.search)它会显示参数source=test,这正是我想要的,但在这种情况下,如果用户在此页面上刷新,搜索参数也会从 react-router 丢失,因为它不在网址。

你们能帮我source=test在 URL 中保持一致吗?

标签: javascriptreactjsreact-router

解决方案


推荐阅读