React Router Dom v6使用登录后导航到条件路径目录



这里我将导航从登录传递到useFirebase

let navigate = useNavigate();
const handleLoginSubmit = (e) => {
loginUser(loginData.email, loginData.password, navigate);
e.preventDefault();
// alert('Login Successful');
}

这是login使用Firebase的用户控制

// user login
const loginUser = (email, password, navigate) => {
setIsLoading(true);
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const destination = navigate?.state?.from || '/';
navigate(destination);
// navigate('/appointment');
// Signed in 
const user = userCredential.user;
// ...
setAuthError('');
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
setAuthError(error.message);
})
.finally(() => setIsLoading(false));
}

我正在尝试在导航中添加条件渲染。当用户登录时,它将重定向到PrivateRoute之前他试图去的组件,干扰用户登录

这假设您正在捕获用户最初试图访问的路由。如果你的代码是而不是这样做,那么这就是捕获重定向的要点;推荐人";验证后使用。

示例:

const AuthWrapper = ({ authenticated }) => {
const location = useLocation();
return authenticated
? <Outlet />
: <Navigate to="/login" replace state={{ from: location }} />;
}

在传递navigate函数和处理登录提交的代码中,访问此处传递的referrer路由状态,并将其传递给loginUser回调。

const navigate = useNavigate();
const { state } = useLocation();
const from = state?.from || "/";
const handleLoginSubmit = (e) => {
e.preventDefault();
loginUser(loginData.email, loginData.password, navigate, from);
};

访问loginUser回调中传递的fromreferrer值。

const loginUser = (email, password, navigate, destination) => {
setIsLoading(true);
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
navigate(destination);
// Signed in 
const user = userCredential.user;
// ...
setAuthError('');
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
setAuthError(error.message);
})
.finally(() => setIsLoading(false));
};

传递onAuthSuccess回调可能会稍微干净一些,但这是主观的。

const navigate = useNavigate();
const { state } = useLocation();
const from = state?.from || "/";
const handleLoginSubmit = (e) => {
e.preventDefault();
loginUser(loginData.email, loginData.password, () => navigate(from));
};

const loginUser = (email, password, onAuthSuccess) => {
setIsLoading(true);
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
onAuthSuccess();
// Signed in 
const user = userCredential.user;
// ...
setAuthError('');
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
setAuthError(error.message);
})
.finally(() => setIsLoading(false));
};

最新更新