[英]Rendering error messages from failed authentication in React-Redux and React Router DOM v4
TL; DR版本:在與陣營,終極版的項目做出反應路由器DOM V4我如何采取從服務器響應axios.put
在./actions
文件,並導入到我的“智能部件”一./containers
所以可以在身份驗證邏輯中使用並呈現為用戶消息(例如,“無效憑據”)。
加長版:所以我一直在學習React-Redux,並從Udemy的Stephen Grider課程開始。 使我感到困惑的原因是,入門/中級課程是在React Router DOM v4
,而高級課程是在React Router v2
。 花費大量時間轉換到v4
。
無論如何,在成功登錄后進行排序后,獲得受保護的路由並重新路由。 我現在遇到的問題是將來自服務器的響應放入Redux-React容器中。
例如,如果登錄憑據錯誤,則登錄API會返回400錯誤。 我應該能夠接受此響應並呈現一條消息,例如The credentials provided are invalid
。 我可以在./actions/authentication
文件中獲取響應,並在console.log()
它,但是無法將其獲取到./containers/authentication/signin.js
。
使用React Router v2
的Stephen Grider tutu可以正常工作。 這是他的項目中的代碼,后面是我的代碼:
// ./actions/index.js
import axios from 'axios';
import { browserHistory } from 'react-router';
import {
AUTH_USER,
UNAUTH_USER,
AUTH_ERROR,
FETCH_MESSAGE
} from './types';
const ROOT_URL = 'http://localhost:3090';
export function signinUser({ email, password }) {
return function(dispatch) {
axios.post(`${ROOT_URL}/signin`, { email, password })
.then(response => {
dispatch({ type: AUTH_USER });
localStorage.setItem('token', response.data.token);
// The below no longer works as of React Router DOM v4
browserHistory.push('/feature');
})
.catch(() => {
dispatch(authError('Bad Login Info'));
});
}
}
export function authError(error) {
return {
type: AUTH_ERROR,
payload: error
};
}
// ./components/auth/signin.js
import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
import * as actions from '../../actions';
class Signin extends Component {
handleFormSubmit({ email, password }) {
// Need to do something to log user in
this.props.signinUser({ email, password });
}
renderAlert() {
if (this.props.errorMessage) {
return (
<div className="alert alert-danger">
<strong>Oops!</strong> {this.props.errorMessage}
</div>
);
}
}
render() {
const { handleSubmit, fields: { email, password }} = this.props;
return (
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<fieldset className="form-group">
<label>Email:</label>
<input {...email} className="form-control" />
</fieldset>
<fieldset className="form-group">
<label>Password:</label>
<input {...password} type="password" className="form-control" />
</fieldset>
{this.renderAlert()}
<button action="submit" className="btn btn-primary">Sign in</button>
</form>
);
}
}
function mapStateToProps(state) {
return { errorMessage: state.auth.error };
}
export default reduxForm({
form: 'signin',
fields: ['email', 'password']
}, mapStateToProps, actions)(Signin);
// ./reducers/index.js
import {
AUTH_USER,
UNAUTH_USER,
AUTH_ERROR,
FETCH_MESSAGE
} from '../actions/types';
import { combineReducers } from 'redux';
import { reducer as form } from 'redux-form';
import authReducer from './auth_reducer';
const rootReducer = combineReducers({
form,
auth: authReducer
});
export default rootReducer;
export default function(state = {}, action) {
switch(action.type) {
case AUTH_USER:
return { ...state, error: '', authenticated: true };
case UNAUTH_USER:
return { ...state, authenticated: false };
case AUTH_ERROR:
return { ...state, error: action.payload };
case FETCH_MESSAGE:
return { ...state, message: action.payload };
}
return state;
}
由於試圖將其與React Router DOM v4
一起使用,因此對Mine進行了少許修改。 我在代碼中添加了一些有趣的注釋。 ./reducers
保持不變,只是import... from
// ./actions/authentication/index.js
import axios from 'axios';
import { ROOT_URL } from '../../../config/settings/secrets.json';
const AUTH_USER = 'auth_user';
const UNAUTH_USER = 'unauth_user';
const AUTH_ERROR = 'auth_error';
export function signinUser({ username, password }) {
return function(dispatch) {
axios.post(`${ROOT_URL}/api/auth/token/`, { username, password })
.then(response => {
dispatch({ type: AUTH_USER });
localStorage.setItem('token', response.data.token);
})
.catch(() => {
dispatch(authError('Bad Login Info'));
});
}
}
export function authError(error) {
// Can console.log() this out and payload does show 'Bad Login Info'
// How to get it innto the signin.js container though?
return {
type: AUTH_ERROR,
payload: error
};
}
// ./containers/authentication/signin.js
import React, { Component } from 'react';
import { reduxForm, Field } from 'redux-form';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import * as actions from '../../actions/authentication';
const renderInput = field => {
const { input, type } = field;
return (
<div>
<input {...input} type={type} className='form-control' />
</div>
);
}
class Signin extends Component {
handleFormSubmit({ username, password }) {
this.props.signinUser({ username, password });
// This is a bad idea since it will pass anything if username and password is entered
// Thus why trying to take the server response and use that
if (username !== undefined && password !== undefined) {
this.props.history.push('/home');
}
}
renderAlert(errorMessage) {
// Cannot console.log() any of this out
// this.renderAlert() doesn't seem to be getting triggered
if (errorMessage) {
return (
<div className="alert alert-danger">
<strong>Oops!</strong> {this.props.errorMessage}
</div>
);
}
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<div className="form-group">
<label>Username:</label>
<Field name='username' type='username' component={renderInput} />
</div>
<div className="form-group">
<label>Password:</label>
<Field name='password' type='password' component={renderInput} />
</div>
{this.renderAlert()}
<button action="submit" className="btn btn-primary">Sign in</button>
</form>
);
}
}
function mapStateToProps(state) {
console.log(state);
return { errorMessage: state.auth.error };
}
Signin = connect(mapStateToProps, actions)(Signin);
Signin = reduxForm({
form: 'signin'
})(Signin);
export default withRouter(Signin);
編輯:咨詢此圖像作為React-Redux數據流的更新。 似乎大多數事情都在努力使其重新回到container
,所以mapStateToProps
是否會mapStateToProps
某種mapStateToProps
而失敗?
噢,天哪,我沒有導出我的操作類型( AUTH_USER
, UNAUTH_USER
和AUTH_ERROR
),以便reducers
可以正確使用它們。
// ./actions/authentication/index.js
export const AUTH_USER = 'auth_user';
export const UNAUTH_USER = 'unauth_user';
export const AUTH_ERROR = 'auth_error';
缺少export
導致了此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.