reactjs - 反应站点导航无需重新加载
问题描述
需要无需重新加载页面即可导航。
例如,通过单击按钮或链接从代码中的某个位置
export default class Test1 extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
this.props.history.push('/my-path')
}
render() {
return (
<a className={this.props.className} onClick={this.onClick}>{this.props.children}</a>
<input type="button" onClick={this.onCLick} value="halo2"/>
);
}
}
但是 this.props.history 是未定义的。
像
export default withRouter(Test1);
产生错误
Error: Invariant failed: You should not use <withRouter(Test1) /> outside a <Router>
通过像这里创建额外的历史类达到最积极的效果如何在 react-router v4 上获取历史?
但它只会更改 URL 而不会实际移动到该位置(不呈现也不执行预期的事件)。
更新 1
甚至尝试将历史推送到全局变量
class DebugRouter extends BrowserRouter {
constructor(props) {
super(props);
App.history = this.history;
然后
App.history.push('/my path');
它也只更改 URL。页面和事件没有变化
解决方案
我通常Link
从'react-router-dom'
.
所以你可以<a>
改为<Link to='/path'>Text</Link>
还要确保您的整个应用程序都在提供程序内部,<BrowserRouter>
否则它们都不起作用。
这是如何使用它的有用链接:https ://reactrouter.com/web/guides/quick-start
推荐阅读
- json - 无法让 json4s 数据提取工作
- java - 我应该在这个 Kotlin 代码中做些什么来打印 1,2,3 ..5 这样的系列数字
- python - Matplot lib:条形图未正确分组
- r - 将 R 内的 GIS 区域联合起来(例如,将县划分为基于核心的统计区域)
- r - 用于将列转换为数字的 for 循环
- wordpress - NextGEN Gallery - 固定链接问题 - urlencode 希伯来语
- unity3d - OnEnable() 方法有替代品吗?
- docker - 在卷默认值中插入 PWD
- python - 从列表中删除多个具有相同小时和分钟的词典?
- java - 伴随对象 Kotlin JNI 中的 UnsatisfiedLinkError