Я создал магазин с redux, чтобы поэкспериментировать с управлением состоянием приложения в React. Пока я просто пытаюсь создать фальшивую аутентификацию при нажатии кнопки «Войти» на странице входа, которая работает, потому что мое состояние isLogged изменилось на true. Но затем, когда я пытаюсь получить доступ к пути, который я защищал, проверяя, является ли isLogged истинным, я получаю false ... почему состояние isLogged не сохраняется при маршрутизации с помощью response-router_dom?
index . js
const store = createStore(
allReducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App/>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
Приложение. js
class App extends Component {
render() {
return (
<Box style={{width: "99.6vw", height: "95.6vh"}}>
<Router>
<SideNavBar/>
<Switch>
<Route exact path={"/"} render={() => <Redirect to={"/login"}/>}/>
<Route path={"/login"} component={LoginPage}/>
<ProtectedRoute path={"/somepage"} component={somePage}/>
</Switch>
</Router>
</Box>
);
}
}
LoginPage. js
class LoginPage extends Component {
render() {
const {dispatch} = this.props;
return (
<LoginPageContainer>
<img src={logo} alt={""} height={"350rem"}/>
<FilledInput placeholder={"Login or email"}/>
<FilledInput placeholder={"Password"}/>
<Button onClick={() => dispatch({ type: "SIGN_IN" })}>
Sign in
</Button>
</LoginPageContainer>
);
}
}
export default connect(null, null)(LoginPage);
ProtectedRoute. js
import {connectProtectedRoute as connect} from "../redux/connectProtectedRoute";
class ProtectedRoute extends Component {
render() {
const {isLogged, component} = this.props;
return (
<Route render={
() => {
if (isLogged)
return (component);
else
return (<Redirect to={"/login"}/>);
}
}/>
);
}
}
ProtectedRoute.propTypes = {
component: PropTypes.elementType.isRequired
};
export default connect(ProtectedRoute);
connectProtectedRoute. js
import {connect} from "react-redux";
function mapStateToProps(state) {
return ({
isLogged: state.isLogged
});
}
export const connectProtectedRoute = connect(mapStateToProps, null);
редукторы . js
const allReducers = combineReducers({
isLogged: isLoggedReducer
});
export default allReducers;
isLoggedReducer. js
const isLoggedReducer = (state = false, action) => {
switch (action.type) {
case "SIGN_IN": return true;
case "SIGN_OUT": return false;
default: return state;
}
}
export default isLoggedReducer;