我在寻找一个简单的登录/注册系统,偶然发现了本教程:
http://jasonwatmore.com/post/2017/09/16/react-redux-user-registration-and-login-tutorial-example
我尝试了一下,并添加了一个真正的mongoDB后端以删除Mock-Backend。这是我第一次做Redux,但是经过很多努力,现在一切正常!您可以在这里查看结果:
只有一件事根本不起作用,我也不知道如何解决它。由于我想避免引导程序,因此我在错误处理方面遇到了很大的问题。
在以下情况下,我想显示Material-Ui的小吃店:
事实上,我的redux文件中已经有一些动作和化简,但是老实说,我只是从教程中复制了它们,却不知道如何使用它们。
以下功能由“登录”按钮触发:
handleSubmit(e) {
e.preventDefault();
this.setState({ submitted: true });
const { username, password } = this.state;
const { dispatch } = this.props;
if (username && password) {
dispatch(userActions.login(username, password))
}
}
这是我的登录功能(user.actions):
function login(username, password) {
return dispatch => {
dispatch(request({ username }));
userService.login(username, password)
.then(
user => {
dispatch(success(user));
history.goBack();
},
error => {
dispatch(failure(error.toString()));
dispatch(alertActions.error(error.toString()));
}
);
};
function request(user) { return { type: userConstants.LOGIN_REQUEST, user } }
function success(user) { return { type: userConstants.LOGIN_SUCCESS, user } }
function failure(error) { return { type: userConstants.LOGIN_FAILURE, error } }
}
警报动作:
import { alertConstants } from '../_constants';
export const alertActions = {
success,
error,
clear
};
function success(message) {
return { type: alertConstants.SUCCESS, message };
}
function error(message) {
return { type: alert, message };
}
function clear() {
return { type: alertConstants.CLEAR };
}
最后是我的alert.constants:
export const alertConstants = {
SUCCESS: 'ALERT_SUCCESS',
ERROR: 'ALERT_ERROR',
CLEAR: 'ALERT_CLEAR'
};
您对我有什么提示或建议吗?
最诚挚的问候:)
编辑:
我忘了在此后续教程中向您展示我的NodeJS全局错误处理程序中间件,以替换正面后端:
module.exports = errorHandler;
function errorHandler(err, req, res, next) {
if (typeof (err) === 'string') {
// custom application error
return res.status(400).json({ message: err });
}
if (err.name === 'ValidationError') {
// mongoose validation error
return res.status(400).json({ message: err.message });
}
if (err.name === 'UnauthorizedError') {
// jwt authentication error
return res.status(401).json({ message: 'Invalid Token' });
}
// default to 500 server error
return res.status(500).json({ message: err.message });
}
答案 0 :(得分:1)
您需要在化简器中为LOGIN_SUCCESS
和LOGIN_FAILURE
设置一个条目,以将Redux存储中的状态设置为可以在组件中使用的状态。
function reducer(state = { status: ''}, action) {
switch (action.type) {
case 'LOGIN_SUCCESS':
return { status: 'LOGGED_IN'}
... ETC
default:
return state
}
}
然后通过mapStateToProps
,您将redux存储的状态映射到组件的道具,并能够像-
const mapStateToProps = (state) => ({
status: state.status
})
this.props.status // LOGGED_IN