javascript - 在位置更改 ReactJs 上保持参数一致
问题描述
我正在使用反应路由器 v4 来更改 ReactJs 中的位置。
this.props.history.push("/profile");
<Link to="/profile" />
上面的代码工作正常。
http://localhost:3000?source=test
现在我想通过使用与上面相同的代码来保持 URL 中的参数一致。
一种方法是我在代码中找到所有出现的地方并添加条件,如果参数source=test
存在,那么也将其附加到 URL 中,但这种方法对我来说看起来不太好,因为我在 every 上添加了条件redirect
,Link
并且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 中保持一致吗?
解决方案
推荐阅读
- jupyter-notebook - 无法加载 jython 内核
- machine-learning - 用 gensim 的 fasttext 的 wrapper 训练词嵌入后,如何嵌入新句子?
- powershell - 更改 Windows Powershell 脚本标题
- reactjs - ReactJS - 我的掷骰子结果不会显示?
- angular - Angular TS SourceMaps 在 Chrome 调试器中不起作用
- node.js - 安装包未显示在我的 package.json 文件中
- javascript - QML WebView 无法运行 javascript
- react-native - RN expo 独立应用程序在 LAN 环境中使用 Authsession,可能吗?
- python - 匹配数据框之间的行并保持顺序
- javascript - 显示隐藏的 div 不是下推其他内容,而是在页面的另一部分