html5-history - URL 更改,但组件未使用 react 渲染 - 打字稿
问题描述
我正在尝试以编程方式更改 URL。
URL 已更改,但页面未刷新/呈现。我试图找到正确的答案超过 2 小时,但没有成功。我看到 URL 确实发生了变化,但组件没有刷新。我的布局组件如下所示:
export default class Layout extends Component {
public render() {
return (
<BrowserRouter>
<section className="layout">
<header>
<Header />
</header>
<main>
<Switch>
<Route path="/login" component={Login} exact />
<Route path="/register" component={Register} exact />
<Route path="/home" component={Main} exact />
<Redirect from="/" to="/home"></Redirect>
</Switch>
</main>
<footer>
<Footer />
</footer>
</section>
</BrowserRouter>
);
}
}
我的主要组件如下所示:
import React, { Component } from "react";
import './main.css'
import history from 'history/browser';
interface MainProps {
registerButton: string,
loginButton: string;
}
export default class Main extends Component<MainProps, any>{
public constructor(props: MainProps) {
super(props);
}
public render() {
return (
<div className="main">This is the Main Section
<div>
<button onClick={this.onRegisterButtonClicked}>REGISTER</button>
<button onClick={this.onLoginButtonClicked}>LOGIN</button>
</div>
</div>);
}
private onLoginButtonClicked = () => {
history.push('/login');
}
private onRegisterButtonClicked = () => {
}
}
解决方案
好的!
我试图删除接口(只是为了扩展没有道具的组件)
export default class Main extends Component<any>
然后命令:“this.props.history ....”被识别。
太棒了,我明白如果我想实现自己的道具,我必须在界面中添加另一个字段:
interface MainProps {
history: BrowserHistory // This is the most important think
registerButton: string,
loginButton: string;
}
然后一切正常:
export default class Main extends Component<MainProps>{
private onRegisterButtonClicked = () => {
this.props.history.push('/register');
}
}
推荐阅读
- python-3.x - 不使用循环的熊猫数据框操作
- docker - 无法调试在 docker 容器中运行的 TestCafe 浏览器
- android - 打开时软键盘在顶部添加空间
- python - 如何将 timedelta 与 pandas df.query() 一起使用?
- angular - Angular:路由重定向问题
- python - 如何在python中一次读取和写入同一个文件
- intellij-idea - Intellij IDEA - 尽管设置了新选项卡,但最终没有打开
- java - 为什么 long 类型的变量在转换之后和在以下代码中转换之前给出不同的答案,因为两者都是 long 类型?
- azure-active-directory - Azure AD:创建具有额外身份的用户
- php - MySQL:如何删除特定用户ID的所有旧记录但保留最新的3条?