我为需要认证的专用路由提供了一些代码。我不知道为什么不将Match传递给子组件。在通过“专用路由”的子组件中,匹配项显示为undefined
可以在子组件中按预期访问常规Route
的匹配,但不能访问PrivateRoute
的匹配。
Routes.js
const Routes = () => {
return (
<Switch>
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={Login} />
<Route exact path="/password/:id?" component={Password} />
<PrivateRoute exact path="/dashboard" component={Dashboard} />
<PrivateRoute exact path="/c/new" component={NewComp} />
<PrivateRoute exact path="/c/:id/manage" component={ManageComp} />
</Switch>
);
};
PrivateRoute.js
import React from "react";
import { Route, Redirect } from "react-router-dom";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Spinner from "../components/Common/Layout/Spinner";
const PrivateRoute = props => {
const {
component: Component,
auth: { isAuthenticated, loading },
...rest
} = props;
if (loading) {
return <Spinner />;
}
if (!isAuthenticated) {
return (
<Redirect
to={{
pathname: "/login",
state: {
alert: "login",
redir: window.location.pathname + window.location.search
}
}}
/>
);
}
return <Component {...props} />;
};
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(mapStateToProps)(PrivateRoute);
ManageComp.js
const ManageComp = ({
loadComp,
competition: { competition, loading },
match
}) => {
useEffect(() => {
console.log(match); /*CONSOLE SHOWS MATCH AS UNDEFINED*/
loadComp();
}, []);
return loading ? <Spinner /> : <div>PAGE HTML</div>;
};
ManageComp.propTypes = {
loadComp: PropTypes.func.isRequired,
competition: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
competition: state.competition
});
export default connect(
mapStateToProps,
{ loadComp }
)(ManageComp);
答案 0 :(得分:3)
在您的PrivateRoute.js中,我认为您需要返回Route
return (
<Route {...rest} render={(props) => (
<Component {...props} />
)}/>
)
这是我的PrivateRoute的示例
const PrivateRoute = ({ component: Component, ...rest }) => {
const isAuthenticated = stores.auth.isAuthenticated
if(isAuthenticated){
return (
<Route {...rest} render={(props) => (
<Component {...props} />
)}/>
)
}
return (
<Route {...rest} render={(props) => (
<Redirect to='/Login'/>
)}/>
)
}