gpt4 book ai didi

javascript - MERN 堆栈 : Using Redux to store whether user is logged in or not

转载 作者:行者123 更新时间:2023-12-02 23:33:56 25 4
gpt4 key购买 nike

我是后端编程新手,正在构建我的第一个全栈项目,并且是第一次使用 Express/Mongoose/Mongo 和 Passport.js。

我已经构建了“使用 Github 登录”功能,并设置了 Passport 的所有内容。现在我想使用 Redux 来存储用户是否已登录。如果用户已登录,我想更改我的导航栏,即如果用户未登录,则一个链接显示“登录”,但如果用户已登录,“登录”链接更改为“个人资料”。

我知道我可以在 React 组件中使用三元运算符来根据用户是否登录来切换链接。

如何使用 Redux 来存储用户是否登录?这是我到目前为止所拥有的:

Redux 操作:

export function loggedIn() {
return {
type: "LOGGED_IN",
loggedIn: false
}
};

Redux reducer :

export default function reducer(state = {
loggedIn: false
}, action) {
switch(action.type) {
case "LOGGED_IN": {
return {
...state,
loggedIn: true
}
}
case "LOGGED_OUT": {
return {
...state,
loggedIn: false
}
}
default: return state;
}

}

我是我的 Express 路线,我使用以下中间件:

// Checks if user is not logged in
const authCheck = (req, res, next) => {
if(!req.user) {
// If user is not logged in, redirect them to login page
res.redirect('/auth/login');
}
else {
// If user is logged in call next in router.get

// Would this be the proper place to dispatch to the Redux store
// whether a user is logged in?
dispatch(loggedIn(true));
// After updating the Redux store call next()
next();
}
};

如何正确存储用户是否登录/注销的状态,然后在 React 组件中访问此状态,以便我可以使用三元运算符选择是否在导航中显示“已登录”或“个人资料”酒吧?

最佳答案

建议不要将后端路由与 reducer 调度混合在一起。我建议在中间件中发回响应 res.status(200).send({loggingIn: true })

// Checks if user is not logged in
const authCheck = (req, res, next) => {
if(!req.user) {
// If user is not logged in, redirect them to login page
res.redirect('/auth/login');
}
else {
res.status(200).send({ loggedIn: true })
next();
}
};

对此中间件的调用可以根据响应调度成功。

 if (res.status === 200) {
dispatch(loggedIn(res.loggedIn));
}
else {
dispatch({ type: 'LOGIN_FAILED'})
}

关于javascript - MERN 堆栈 : Using Redux to store whether user is logged in or not,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56367095/

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