Reactjs 为什么我的重定向在验证后不起作用?
下面的代码试图验证一些东西,然后需要重定向到主页Reactjs 为什么我的重定向在验证后不起作用?,reactjs,firebase,react-router,Reactjs,Firebase,React Router,下面的代码试图验证一些东西,然后需要重定向到主页 const EmailLink=()=>{ 常量testEmailAuth=()=>{ if(firebase.auth().isSignInWithEmailLink(window.location.href)){ 如果(!电子邮件){ 返回null; } 火基 .auth() .signInWithEmailLink(电子邮件,window.location.href) .然后(函数(结果){ window.location.href='/'
const EmailLink=()=>{
常量testEmailAuth=()=>{
if(firebase.auth().isSignInWithEmailLink(window.location.href)){
如果(!电子邮件){
返回null;
}
火基
.auth()
.signInWithEmailLink(电子邮件,window.location.href)
.然后(函数(结果){
window.location.href='/';
//
})
.catch(函数(错误){
console.log('error'+error);
});
}
};
返回(
{testEmailAuth()}
);
};
我正在尝试从react router dom
使用redirect
重定向。
它不起作用
它正在使用window.location.href='/'
。
我能知道为什么吗如何使事情与重定向一起工作
<Switch>
<Route path="/finishedSignUp" component={EmailLink}/>
</Switch>
export default withRouter(RootComponent);
使用路由器导出默认值(RootComponent);
这段代码不在路由器提供程序内部,
无法工作
如果您无法将此代码放入路由器提供程序包装的字段中,您可以为路由器创建实例,并在应用程序中的任何位置使用它:
您还需要向路由器提供商提供此浏览器历史记录实例
App.jsx
从“历史”导入{createBrowserHistory};
export const browserHistory=createBrowserHistory();
常量应用=()=>{
返回。。。;
};
稍后,您可以在代码中使用它:
从'App'导入{browserHistory};
火基
.auth()
.signInWithEmailLink(电子邮件,window.location.href)
.然后(函数(结果){
window.localStorage.removietem('emailForSignIn');
browserHistory.push('/');
})
.catch(函数(错误){
console.log('error'+error);
});
您还需要在路由器内提供浏览器历史记录的此实例:,如所述:
渲染将导航到新位置。新的
位置将覆盖历史堆栈中的当前位置,如
服务器端重定向(HTTP 3xx)不起作用
例如:
function App() {
const [redirect, setRedirect] = useState(null);
const someFunction = () => {
//Set redirect to display Redirect and go to /
setRedirect("/");
};
return redirect ? (
<Redirect to={redirect} />
) : (
<div>{/** rest of your app */}</div>
);
}
函数应用程序(){
const[redirect,setRedirect]=useState(null);
常量someFunction=()=>{
//设置重定向以显示重定向并转到/
setRedirect(“/”);
};
返回重定向(
) : (
{/**应用程序的其余部分*/}
);
}
因为电子邮件链接
由它接收的路由
组件在交换机
中呈现。使用传递的history
对象,使用history.replace()
处理重定向
请注意,您不应该从“渲染”发出异步调用和副作用,在组件装载时使用useffect
钩子来处理此问题
const EmailLink = ({ history, match }) => {
useEffect(() => {
const testEmailAuth = () => {
if (firebase.auth().isSignInWithEmailLink(match.url)) {
if (!email) {
return null;
}
firebase
.auth()
.signInWithEmailLink(email, match.url)
.then(function(result) {
history.replace('/'); // <-- replace === redirect
})
.catch(function(error) {
console.log('error ' + error);
});
}
};
testEmailAuth();
}, []);
return (
<div className="EmailLink" />
);
};
const EmailLink=({history,match})=>{
useffect(()=>{
常量testEmailAuth=()=>{
if(firebase.auth().isSignInWithEmailLink(match.url)){
如果(!电子邮件){
返回null;
}
火基
.auth()
.signiWithEmailLink(电子邮件,match.url)
.然后(函数(结果){
历史记录。替换(“/”);//这不是JSX的返回/呈现方式。您可以发布完整的组件代码吗?组件是否在路由器中呈现?@drewrese I更新了代码,并且在应用程序中路由器中呈现了EmailLink
?电子邮件链接位于
语句之间,并且正在使用withRouter导出
使用react路由器dom