とルータのV4を反応させ、私は、ユーザーがログインしていない場合はリダイレクトするために、民間と保護ルートを利用することにしたい。はReduxの保護されたルートと認証
私はこのルート要素を持っています:
class Routes extends Component {
render() {
const { auth } = this.props;
// so checks against isAuthenticated can pass
if (auth.isAuthenticated !== undefined) {
return (
<div>
<Route exact component={() => <Home />} />
<PublicRoute
authed={() => auth.isAuthenticated}
path="/login"
component={(routerProps) => <Login {...routerProps} />}
/>
<PublicRoute
authed={() => auth.isAuthenticated}
path="/register"
component={(routerProps) => <Register {...routerProps} />}
/>
<PrivateRoute
authed={() => auth.isAuthenticated}
path="/dashboard"
component={Dashboard}
/>
</div>
);
} else {
return <div></div>
}
}
}
function mapStateToProps(state) {
return {
auth: state.auth
}
}
export default withRouter(connect(mapStateToProps)(Routes));
、それはこのように実装されています。
class Main extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
store.dispatch(checkAuth());
}
render() {
return (
<Provider store={store}>
<Router>
<Theme>
<Routes />
</Theme>
</Router>
</Provider>
);
}
}
これはPrivateRouteです:
export function PrivateRoute({ component: Component, authed, ...rest }) {
const isAuthenticated = authed();
return (
<Route
{...rest}
render={props =>
isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
}
何、そのauth
小道具を渡すための最良の方法である、それは私がルート・コンポーネントを接続し、そこからauth
を渡すか、私はどこかから渡される必要がある場合は、多分それを必要とする各コンポーネントを接続して、読んでokですそこから?また、このアプローチは、/dashboard/settings
のようなネストされたルートでどのように動作しますか?おかげ
場合、あなただけの直接' PrivateRoute'を接続することもできます。 –
@RobertFarleyはい、私はそれを試みます、ありがとう! – Case09
@RobertFarleyしかし、多くのPrivateRouteに接続するとパフォーマンスに問題がありますか? –