gpt4 book ai didi

javascript - 如何在 react redux 中添加 protected 路由

转载 作者:行者123 更新时间:2023-12-04 11:18:19 25 4
gpt4 key购买 nike

我创建了一个登录组件,其中包含所有逻辑内容。
登录 reducer 是:

const openState = {
loggedIn: null,
user: null
}

export default (state = openState, action) => {
switch (action.type) {
case LOGIN:
return { ...state, loggedIn: true, user: action.payload }
case LOGOUT:
return { ...state, loggedIn: false, user: null }
default:
return openState
}
}
那个行动 :
export const logIn = (user) => {
return {
type: LOGIN,
payload: user
}
}

export const logOut = () => {
return {
type: LOGOUT
}
}
一切正常,但我不确定如何通过 loggedInuser将 Action 中的 Prop 放入路由组件中,以保护所有路由:
const MainRoutes = props => {
const { loggedIn } = props;

console.log(props.loggedIn)

return (
<Router history={history}>
<Baseline />
<Menu/>
<Container maxWidth="md">
<Switch>
<Route exact path="/Login" component={Login} />
<Route exact path="/Carousel" component={Carousel} />
<Route exact path="/Stepper" component={Stepper} />
<Route component={NotFound} />
</Switch>
</Container>
</Router>
);
}

const mapStateToProps = (state) => {
return { loggedIn: state.loggedIn };
};

export default connect(mapStateToProps)(MainRoutes);
如果我控制台记录 loggedIn我得到未定义的 Prop :|
基于 loggedIn我可以在路由组件中创建一个逻辑。

最佳答案

您可以简单地定义一个自定义 ProtectedRoute将连接到 redux 状态的组件。在您的情况下,它应该映射 state.auth.loggedInstate.auth.user Prop 和执行Redirect如果这些值是虚假的:

import React from "react";
import { Route, Redirect } from "react-router-dom";
import PropTypes from "prop-types";


const ProtectedRoute = (props) => {
const { redirectPath, component, user, loggedIn, ...routeProps} = props;
const Component = component;
const isAccessible = Boolean(user) && loggedIn;

return (
<Route
{...routeProps}
render={props => {
if (isAccessible) return <Component {...props} />;
return <Redirect to={{ pathname: redirectPath || "/Login" }} />;
}}
/>
);
};

ProtectedRoute.propTypes = {
path: PropTypes.string.isRequired,
redirectPath: PropTypes.string,
component: PropTypes.oneOfType([
PropTypes.shape({ render: PropTypes.func.isRequired }),
PropTypes.func
]),
};

const mapStateToProps = (state) => {
return {
loggedIn: state.auth.loggedIn,
user: state.auth.user
};
};

export default connect(mapStateToProps)(ProtectedRoute);
有了这个你的 MainRoutes不需要 connect不再:
const MainRoutes = props => {
return (
<Router history={history}>
...
<Container maxWidth="md">
<Switch>
<Route exact path="/Login" component={Login} />
<ProtectedRoute exact path="/Carousel" component={Carousel} />
<ProtectedRoute exact path="/Stepper" component={Stepper} />
<Route component={NotFound} />
</Switch>
</Container>
</Router>
);
}

export default MainRoutes;
更新:
如果你想保留 auth页面刷新后的状态,您需要对 redux 商店进行一些额外的设置。主要思想是订阅每个 Action 并将新的状态副本放入 localStoragecookies还要坚持 initialState在您的应用启动之前从选定的存储中获取。这是一个例子:
function getFromStorage(key) {
try {
return JSON.parse(window.localStorage.getItem(key)) || {};
} catch (err) {
return {};
}
}

const initialState = getFromStorage("APP_STATE");

const store = createStore(
rootReducer,
initialState, // should go after root reducer
...
);

store.subscribe(() => {
window.localStorage.setItem("APP_STATE", JSON.stringify(store.getState()));
});
这是有效的 sandbox (由 SuleymanSah 引导)

关于javascript - 如何在 react redux 中添加 protected 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66206075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com