gpt4 book ai didi

reactjs - React-router 4 和以编程方式重定向

转载 作者:行者123 更新时间:2023-12-03 13:47:31 25 4
gpt4 key购买 nike

当用户转到登录组件时,我试图将用户重定向到他来自的地方。实际上,现在我很乐意重定向到已知的网址。在本例中为“/dashboard”。

我的应用程序以 app.js 开头,路由定义为:

render() {
return (
<div>
<Router>
<div>
<Navbar />
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
<Route path='/contact' component={Contact} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
<Route path="/profile" component={Profile} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/accounts" component={AccountList} />
<Route path="/account" component={Account}/>
</div>
</Router>
</div>
)
}

我已导航至“登录”,并且用户已输入其凭据。我已经针对 WebAPI 调用进行了验证,并且成功了。所以我想重定向。

我正在这样做:

message = "Welcome, " + Auth.Auth.firstname();
history.push("/dashboard");

我的登录屏幕导入有:

import history from '../../helpers/history.js';

history.js 只是:

import createHistory from 'history/createHashHistory'
export default createHistory();

推送已执行,但屏幕不刷新。 URL 只需更新为:

http://localhost:8080/login#/dashboard

如果我点击“仪表板”导航按钮,URL 会更改为:

http://localhost:8080/dashboard

我的屏幕加载仪表板。

当我需要时,如果有问题,我应该如何重定向?

最佳答案

您需要扭曲组件withRouter,然后使用this.props.history.push('/dashboard')

no need to import history from '../../helpers/history.js';

了解更多关于withRouter的信息

You can get access to the history object's properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

import React from "react";
import { withRouter } from "react-router-dom";

class AppA extends React.Component {
componentDidMount(){
setTimeout(()=>{
this.props.history.push("/b");
},1000)
}
render() {
return (
<div>
<h1> Component A will redirect after 1 sec </h1>
</div>
)
}
}
export default withRouter(AppA);

Edit kk8pj61y0o

关于reactjs - React-router 4 和以编程方式重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49714432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com