我想将我的用户重定向到他在登录后输入的任何 url 例如;我的用户在浏览器中输入 http://localhost:3000/login/tickets , 如果他没有登录,我需要程序加载登录页面,登录后,程序重定向到这个页面,我可以用一个页面来做,但我希望它是动态的,像这样。
isAuthenticated()
? (
<Component {...props} />
) : <Redirect to=`/login?next=${this.props.location.search}` />
)}
很快这个重定向将加载带有标签 next 的登录页面
最佳答案
我的解决方案基本上是按照您的描述进行操作。如果需要用户登录,我做了一个 HOC 来包装我的路由组件:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter, Redirect } from 'react-router-dom';
/**
* Higher-order component (HOC) to wrap restricted pages
*/
export default function LoggedInOnly(BaseComponent) {
class Restricted extends Component {
state = {};
static getDerivedStateFromProps(nextProps) {
const { history, location } = nextProps;
if (!nextProps.isLoggedIn) {
history.replace({ pathname: '/signin', search: `dest=${encodeURIComponent(location.pathname)}` });
}
return null;
}
render() {
const { location, staticContext } = this.props;
if (this.props.isLoggedIn) return <BaseComponent {...this.props} />;
const destinationURL = `/signin?dest=${encodeURIComponent(location.pathname)}`;
if (staticContext) staticContext.url = destinationURL;
return <Redirect to={destinationURL} />;
}
}
const mapStateToProps = state => ({
isLoggedIn: !!state.globalUserState.loggedInUserEmail,
});
return withRouter(connect(mapStateToProps)(Restricted));
}
在我的案例中,我还在静态上下文中设置了 url,这样我就可以在服务器端渲染中适本地处理重定向。如果您不这样做,则可以忽略该部分。
不过,为了使用它,我在 SSR 渲染函数之后重定向,如下所示:
if (context.url) {
console.log(`Redirecting to URL ${context.url}`);
return res.redirect(context.url);
}
使用它的路线看起来像:
<Route path="/preferences" component={LoggedInOnly(SettingsView)} />
在我的登录页面上,我获取 url 参数以查看是否有目的地。如果有,我会在登录成功时重定向到那里。
我使用查询字符串和位置的搜索组件执行此操作:
const { destination } = queryString.parse(props.location.search);
以上假设您使用 withRouter 来获取 props 中的位置信息。
在客户端身份验证成功后,如果目标存在,我只需重定向到目标:
window.location.href = this.props.destination;
您也可以使用 history.push 或类似工具来完成上述操作。
在我的例子中,如您所见,我使用 redux 来跟踪登录的用户状态。
关于javascript - 如何在重定向登录后重定向到任何网址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58439671/