react form example reactjs redux react-redux axios redux-thunk

reactjs - react - redux form crud example



React Redux Axios: solicitud POST que no recibe credenciales del estado redux (1)

Parece que empNum y la contraseña no se configuran en el estado. Esto se debe a que el objeto de acción devuelto por credChange no se despacha, por lo que nunca se llama al reductor:

// dispatch calls the reducer which updates the state dispatch(actionCreator()) // returns an action object, doesn''t call reducer actionCreator()

Puede enviar acciones automáticamente llamando a un creador de acciones encuadernado :

// calls the reducer, updates the state const boundActionCreator = () => {dispatch(actionCreator())} // call boundActionCreator in your component boundActionCreator()

mapDispatchToProps se puede usar para definir creadores de acciones enlazadas (para pasarlas como accesorios):

const mapDispatchToProps = (dispatch) => { return { credChange: ({ prop, value }) => {dispatch(credChange({prop, value})}, loginUser: ({ empNum, password }) => {dispatch(loginUser({empNum, password})}, logoutUser: () => {dispatch(logoutUser()}, } } export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);

Esto debería resolver el problema de actualización del estado, permitiendo que los accesorios que leen el estado (empNumber, contraseña, etc.) también se actualicen.

He estado trabajando en la autenticación con mi proyecto. Tengo un backend REST api que sirve tokens JWT. Mi pila frontal es ReactJS, Redux, Axios y Redux Thunk.

Mi pregunta es por qué cuando envío mi formulario, ¿no envía credenciales?

Pero cuando la consola registra la acción y la carga útil en credChange , parece ser correcta. ¿No estoy estableciendo el estado en alguna parte? Además, axios no detecta el error de 400 Bad Request.

Aquí está mi código:

AuthActions.js

export const credChange = ({ prop, value }) => { return { type: CRED_CHANGE, payload: { prop, value }, }; }; export const logoutUser = () => { return (dispatch) => { dispatch({ type: LOGOUT_USER }); }; }; const loginSuccess = (dispatch, response) => { dispatch({ type: LOGIN_USER_SUCCESS, payload: response.data.token, }); }; const loginError = (dispatch, error) => { dispatch({ type: LOGIN_USER_ERROR, payload: error.response.data, }); }; export const loginUser = ({ empNum, password }) => { return (dispatch) => { dispatch({ type: LOGIN_USER }); axios({ method: ''post'', url: ''http://127.0.0.1:8000/profiles_api/jwt/authTK/'', data: { emp_number: empNum, password, }, }) .then(response => loginSuccess(dispatch, response)) .catch(error => loginError(dispatch, error)); }; };

AuthReducer.js

const INITIAL_STATE = { empNum: '''', password: '''', empNumErr: null, passwordErr: null, authTK: null, loading: false, }; export default (state = INITIAL_STATE, action) => { switch (action.type) { case CRED_CHANGE: return { ...state, [action.payload.prop]: action.payload.value }; case LOGIN_USER: return { ...state, ...INITIAL_STATE, loading: true, }; case LOGOUT_USER: return { ...state, INITIAL_STATE, }; case LOGIN_USER_SUCCESS: return { ...state, ...INITIAL_STATE, authTK: action.payload, }; case LOGIN_USER_ERROR: return { ...state, ...INITIAL_STATE, empNumErr: action.payload.emp_number, passwordErr: action.payload.password, }; default: return state; } };

LoginForm.js

import React, { Component } from ''react''; import { connect } from ''react-redux''; import { credChange, loginUser, logoutUser, } from ''../Actions''; class LoginForm extends Component { constructor() { super(); this.onFormSubmit = this.onFormSubmit.bind(this); this.renderEmpNumErr = this.renderEmpNumErr.bind(this); this.empNumChange = this.empNumChange.bind(this); this.passwordChange = this.passwordChange.bind(this); } onFormSubmit() { const { empNum, password } = this.props; this.props.loginUser({ empNum, password }); } empNumChange(text) { this.props.credChange({ prop: ''empNum'', value: text.target.value }); } passwordChange(text) { this.props.credChange({ prop: ''password'', value: text.target.value }); } renderEmpNumErr() { if (this.props.empNumErr) { return ( <p> {this.props.empNumErr} </p> ); } return null; } render() { return ( <div> <form onSubmit={this.onFormSubmit}> <label htmlFor="numberLabel">Employee Number</label> <input id="numberLabel" type="password" value={this.props.empNum} onChange={this.empNumChange} /> <label htmlFor="passLabel">Password</label> <input id="passLabel" type="password" value={this.props.password} onChange={this.passwordChange} /> <button type="submit">Login</button> </form> {this.renderEmpNumErr()} </div> ); } } const mapStateToProps = ({ counter }) => { const { empNum, password, loading, empNumErr, passwordErr, authTK, } = counter; return { empNum, password, loading, empNumErr, passwordErr, authTK, }; }; export default connect(mapStateToProps, { credChange, loginUser, logoutUser })(LoginForm);

Después de enviar formulario con credenciales

La consola dice:

POST XHR http://127.0.0.1:8000/profiles_api/jwt/authTK/ [HTTP / 1.0 400 Solicitud incorrecta 5ms]

Y los datos sin procesar de la solicitud POST están en blanco, por lo tanto, no se enviaron credenciales.

{"emp_number": ["Este campo es obligatorio"], "contraseña": ["Este campo es obligatorio"]]

EDITAR Si hay alguna otra información que pueda proporcionar, dígalo, pero creo que esto debería ser suficiente.