无需重新加载即可反应站点导航
React site navigating without reload
需要无需重新加载页面即可导航的功能。
例如从代码中的某个地方点击按钮或link
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>
通过创建更多历史记录达到的最积极效果 class 就像这里
但它只会改变 URL 而不会实际移动到那个位置(不呈现也不执行预期的事件)。
更新 1
甚至尝试将历史推送到全局变量
class DebugRouter extends BrowserRouter {
constructor(props) {
super(props);
App.history = this.history;
比
App.history.push('/my path');
它也只改变URL。页面和事件没有变化
我通常使用 'react-router-dom'
中的 Link
。
所以您只需将 <a>
更改为 <Link to='/path'>Text</Link>
还要确保您的整个应用程序都在提供商 <BrowserRouter>
内,否则 none 的应用程序将正常工作。
这是有用的link使用方法:https://reactrouter.com/web/guides/quick-start
需要无需重新加载页面即可导航的功能。
例如从代码中的某个地方点击按钮或link
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>
通过创建更多历史记录达到的最积极效果 class 就像这里
但它只会改变 URL 而不会实际移动到那个位置(不呈现也不执行预期的事件)。
更新 1
甚至尝试将历史推送到全局变量
class DebugRouter extends BrowserRouter {
constructor(props) {
super(props);
App.history = this.history;
比
App.history.push('/my path');
它也只改变URL。页面和事件没有变化
我通常使用 'react-router-dom'
中的 Link
。
所以您只需将 <a>
更改为 <Link to='/path'>Text</Link>
还要确保您的整个应用程序都在提供商 <BrowserRouter>
内,否则 none 的应用程序将正常工作。
这是有用的link使用方法:https://reactrouter.com/web/guides/quick-start