【发布时间】:2022-01-05 03:19:30
【问题描述】:
为了只允许经过身份验证的用户访问,我创建了一个组件 PrivateRoute,如 here 所述。一切正常,但它给了我一个警告,“位置”未定义。
import React from 'react';
import PropTypes from 'prop-types';
import { Redirect, Route } from 'react-router-dom';
import auth from '../../hooks/login/auth';
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={(props) => (
auth.getToken() !== null ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/log_in',
state: { from: props.location },
}}
/>
)
)}
/>
);
PrivateRoute.propTypes = {
component: PropTypes.any.isRequired, // eslint-disable-line
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}).isRequired,
};
export default PrivateRoute;
<Switch>
<Route exact path="/" component={LogIn} />
<Route exact path="/log_in" component={LogIn} />
<PrivateRoute exact path="/dashboard" component={Dashboard} />
</Switch>
如果我在渲染方法中创建控制台日志,则始终定义位置。怎么回事?
<Route
{...rest}
render={(props) => {
console.log('LOCATION', props.location);
return auth.getToken() !== null ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/log_in',
state: { from: props.location },
}}
/>
);
}}
/>
我试图给 location 一个默认值,但是整个页面都是空白的。
PrivateRoute.propTypes = {
component: PropTypes.any.isRequired, // eslint-disable-line
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}),
};
PrivateRoute.defaultProps = {
location: {
pathname: '',
},
};
这里有什么问题?当任何控制台日志输出显示已定义的位置对象时,位置如何可能未定义?
【问题讨论】:
标签: javascript reactjs react-router react-router-dom react-proptypes