Я начинающий с реаги-редукс , и я хочу реализовать авторизацию.Вот мой контейнер с именем RestrictedRoute , который проверяет, разрешен ли целевой URI пользователю или нет.Теперь проблема в том, что состояние по умолчанию isAllowed было проверено как ложное.когда компонент визуализируется, состояние isAllowed по умолчанию было ложным значением, и рендеринг проверяет, является ли isAllowed ложным, затем перенаправляет на компонент 403 .Я хочу инициировать свое действие checkComponent () перед рендерингом при каждом изменении маршрута, так что оно не будет ложным в разрешенных URI из БД после запроса API при каждом изменении маршрута
class RestrictedRoute extends Component {
constructor(props) {
super(props);
this.state = {
componentRoute:''
}
}
componentWillMount() {
const componentRoute = this.props.pathname;
this.props.getUser();
this.props.checkComponent(componentRoute);
}
componentDidMount() {
if(this.state.componentRoute === ''){
// const componentRoute = this.props.pathname;
}else{
}
// console.log("restrictions");
}
componentDidUpdate(prevProps) {
// console.log("prevProps", prevProps);
// console.log("next props", this.props);
if (this.props.pathname !== prevProps.pathname && this.pathname !== "/invalid_page") {
// alert("hello");
const componentRoute = this.props.pathname;
this.props.getUser();
// console.log(componentRoute);
this.props.checkComponent(componentRoute);
}
}
render() {
const Component = this.props.component;
// console.trace("restricted route allowed", this.props.rest);
return (
<Route
// {...this.props.rest}
render={
(props) => {
if (this.props.authUser===null) {
return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
} else {
// alert("allowed", this.props.isAllowed);
if(this.props.isAllowed || this.props.location.pathname==="/invalid_page"){
return <Component {...props} />;
}else{
// alert("usman hafeez");
return <Redirect to={{ pathname: '/invalid_page', state: { from: props.location } }} />
}
}
}
} />
)
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
checkComponent: checkComponent,
getUser: getUser
}, dispatch);
}
var mapStateToProps = ({ routing ,auth}, otherProps) => {
// console.log("restricted route", routing);
// console.log("restricted auth", auth);
// console.log("restricted other", otherProps);
return {
// routing: routing,
pathname: routing.location.pathname,
authUser: auth.authUser,
isAllowed: auth.isAllowed
};
}
export default connect(mapStateToProps, mapDispatchToProps)(RestrictedRoute);
здесьМой checkComponent Действие
export const checkComponent = (componentUri) => {
console.log("KSDJ")
return (dispatch) => {
// alert("hello");
RestService.checkComponent(componentUri).then((resp) => {
if (RestService.checkAuth(resp.data)) {
if (resp.data.status === true) {
dispatch({
type: COMPONENT_ALLOWED,
payload: resp.data.ComponentAllowed
});
} else {
dispatch({
type: INVALID_RESPONSE
});
}
} else {
dispatch({
type: INVALID_TOKEN
});
}
});
}
};
вот мой файл редуктора auth.js
import {
HIDE_MESSAGE,
INIT_URL,
ON_HIDE_LOADER,
ON_SHOW_LOADER,
SHOW_MESSAGE,
LOGIN_USER_SUCCESS,
LOGOUT_USER_SUCCESS,
LOGIN_FAILED,
INVALID_TOKEN,
COMPONENT_ALLOWED,
ACCESS_DENIED,
UPDATE_PROFILE,
GET_USER
} from "constants/ActionTypes";
import RestService from '../services/RestServices';
import { message } from "antd";
const INIT_STATE = {
loader: false,
alertMessage: '',
showMessage: false,
initURL: '',
isAllowed: true,
authUser: localStorage.getItem('authUser'),
};
export default (state = INIT_STATE, action) => {
// console.log("auth.js");
// console.log("states");
// console.log("auth user state");
// console.log(state.authUser);
// console.log("actions");
// console.log(action.type);
switch (action.type) {
case LOGIN_USER_SUCCESS: {
// console.log("logged in");
return {
...state,
loader: false,
authUser: action.payload
}
}
case GET_USER: {
return {
...state,
authUser:{
id: action.payload.id,
connected_dealer: action.payload.connected_dealer,
email: action.payload.email,
dealerId: action.payload.dealerId,
firstName: action.payload.firstName,
lastName: action.payload.lastName,
name: action.payload.name,
type: action.payload.type,
dealer_pin: action.payload.dealer_pin
}
}
}
case LOGIN_FAILED: {
// console.log({
// ...state,
// alertMessage: action.payload.msg,
// showMessage: true,
// loader: false
// });
return {
...state,
alertMessage: action.payload.msg,
showMessage: true,
loader: false
}
}
case INIT_URL: {
return {
...state,
initURL: action.payload
}
}
case LOGOUT_USER_SUCCESS: {
return {
...state,
authUser: {
id: null,
connected_dealer: null,
email: null,
dealerId: null,
firstName: null,
lastName: null,
name: null,
token: null,
type: null
},
initURL: '/',
loader: false
}
}
case UPDATE_PROFILE: {
if (action.response.status) {
message.success(action.response.msg);
state.authUser.firstName = action.response.data.first_Name;
state.authUser.lastName = action.response.data.Last_Name;
localStorage.setItem('firstName', action.response.data.first_Name);
localStorage.setItem('lastName', action.response.data.Last_Name);
// console.log('user detail',action.response);
// console.log('user state',state.authUser);
}
else {
message.error(action.response.msg);
}
return {
...state,
loader: false,
}
}
break;
case INVALID_TOKEN: {
RestService.authLogOut();
return {
...state,
alertMessage: "Login expired",
showMessage: true,
authUser: {
id: null,
connected_dealer: null,
email: null,
dealerId: null,
firstName: null,
lastName: null,
name: null,
token: null,
type: null
},
initURL: '/',
loader: false
}
}
case SHOW_MESSAGE: {
return {
...state,
alertMessage: action.payload,
showMessage: true,
loader: false
}
}
case HIDE_MESSAGE: {
return {
...state,
alertMessage: '',
showMessage: false,
loader: false
}
}
case ON_SHOW_LOADER: {
return {
...state,
loader: true
}
}
case ON_HIDE_LOADER: {
return {
...state,
loader: false
}
}
case COMPONENT_ALLOWED: {
// console.log("dsfsdfsdf",action.payload)
return {
...state,
isAllowed: action.payload
}
break;
}
case ACCESS_DENIED: {
return {
...state,
initURL: '/invalid_page'
}
break;
}
default:
return state;
}
}
, объединяющий index.js
import { combineReducers } from "redux";
import { routerReducer } from "react-router-redux";
import Auth from "./Auth";
const reducers = combineReducers({
auth: Auth,
});
export default reducers;