【发布时间】:2018-11-23 20:00:18
【问题描述】:
如果我对我的 API 执行所有身份验证请求 不是直接在 react-redux 的“handleSubmit”函数内部,而是在自定义 redux 操作中,我遇到了将服务器收到的任何错误作为回复显示的问题。
这是身份验证操作 (authActions.js):
export const loginUser = userData => dispatch => {
axios
.post("auth/local/signin")
.then(res => {
dispatch({
type: SET_CURRENT_USER,
payload: res
});
})
.catch(err => {
dispatch({
type: GET_ERRORS,
payload: err.response.data
});
});
};
authReducer.js
import { SET_CURRENT_USER } from "../actions/types";
const initialState = {
isAuthenticated: false,
user: {}
};
export default function(state = initialState, action) {
switch (action.type) {
case SET_CURRENT_USER:
return {
...state,
isAuthenticated: Object.keys(action.payload).length > 0,
user: action.payload
};
default:
return state;
}
}
errorReducer.js
import { GET_ERRORS, CLEAR_ERRORS } from "../actions/types";
const initialState = {};
export default function(state = initialState, action) {
switch (action.type) {
case GET_ERRORS:
return action.payload;
case CLEAR_ERRORS:
return {};
default:
return state;
}
}
当时唯一想到的就是连接redux,还有redux-form这个组件,然后去通过“new SubmissionError(errors)”报一个可能的错误。但这不适用于第一次提交。
class SignInForm extends Component {
handleSubmit = values => {
const userData = {
username: values.username,
password: values.password
};
this.props.loginUser(userData);
const { errors } = this.props;
console.log(errors);
errors.username = errors.user;
if (errors) throw new SubmissionError(errors);
};
render() {
const { valid, handleSubmit, submitting } = this.props;
return (
<View>
...
</View>
);
}
}
const mapStateToProps = state => ({
auth: state.auth,
errors: state.errors
});
const form = reduxForm({
form: "Login",
validate,
asyncValidate,
asyncChangeFields: ["username"]
})(SignInForm);
export default connect(
mapStateToProps,
{ loginUser }
)(form);
【问题讨论】:
标签: reactjs react-native redux react-redux redux-form