当我使用history.push(/ myappointment)时,页面路由到MyAppointment组件。现在,在MyAppointment组件中,有一个按钮,单击该按钮时,我调用函数“ Click”,在该函数中执行history.push(/ newAppointment)进入“ newAppointment”组件,但这一次错误显示为: -
MyAppointment.tsx:53 Uncaught TypeError: Cannot read property 'history' of undefined
两个组件的一些行是:-
第一个组件的代码是:-
interface ILoginPageProps {
history: any;
}
class Login extends React.Component<ILoginPageProps, {}> {
componentDidUpdate() {
const { history } = this.props;
history.push({"/myappointment"});
}
}
MyAppointment的代码是:-
interface IProps {
history: any;
}
rightClick() {
//console.log("hii");
const { history } = this.props;
history.push("/newAppointment");
}
路由文件代码为:-
export default class App extends React.Component {
render() {
return (
<MuiThemeProvider muiTheme={getMuiTheme(constants)}>
<Switch>
<Route exact path="/" component={Login} />
<Route path="/myAppointment" component={MyAppointment} />
<Route
path="/myAppointment/newAppointment"
component={NewAppointment}
/>
</Switch>
</MuiThemeProvider>
);
}
}
非常感谢您的帮助。
答案 0 :(得分:0)
这部分可能有错字。您正在尝试从history
破坏this.props.history
。
const { history } = this.props.history; // this probably should be `this.props` instead
history.push("/newAppointment");
答案 1 :(得分:0)
您要么希望 Link 组件将其路由到另一个页面。
提供围绕应用程序的声明式,可访问的导航
import { Link } from "react-router-dom";
...
<Link to="/newAppointment" />
或者,如果您要以编程方式推送,则必须使用 withRouter HOC
包装组件您可以访问历史记录对象的属性和最近的属性 通过withRouter高阶组件进行路由匹配。与路由器 会将经过更新的比赛,位置和历史道具传递给已包装的 组件在渲染时显示。
@withRouter
class Login extends React.Component
....
或者如果您愿意
class Login extends React.Component
...
export default withRouter(Login);