【发布时间】:2021-03-29 12:02:50
【问题描述】:
初学者问题 ReactJs 和路由器 V6,我学习了 react-router-dom,现在我似乎无法导航到另一个路径/页面
我有这些路线:
const routes = [
{
path: 'app',
element: <DashboardLayout />,
children: [
{ path: 'account', element: <AccountView /> },
{ path: 'search', element: <SearchListView /> },
{ path: 'dashboard', element: <DashboardView /> },
{ path: 'create', element: <CreateContentView /> },
{ path: 'submissions', element: <SubmissionsView /> },
{ path: 'inbox', element: <InboxView /> },
{ path: 'settings', element: <SettingsView /> },
{ path: 'login', element: <LoginView /> },
{ path: 'register', element: <RegisterView /> },
{ path: '*', element: <NotFoundView /> },
{ path: '/', element: <DashboardView /> },
],
},
{
path: '/',
element: <ContentLayout />,
children: [
{ path: '404', element: <NotFoundView /> },
{ path: '*', element: <NotFoundView /> },
],
},
];
export default routes;
当我在这里“https://localhost:6545/app/login”时
在图片中,我按下“注册”,它应该会出现在此处:
“https://localhost:6545/app/register”
但它没有转到“https://localhost:6545/app/login/register”,那就是<NotFoundView />
什么时候应该去:
https://localhost:6545/app/register
这是我的代码:
import React from 'react';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import * as Yup from 'yup';
import { Formik } from 'formik';
import {
Box,
Button,
Container,
Grid,
Link,
TextField,
Typography,
makeStyles
} from '@material-ui/core';
import FacebookIcon from '../../icons/Facebook';
import GoogleIcon from '../../icons/Google';
import Page from '../../components/Page';
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: theme.palette.background.dark,
height: '100%',
paddingBottom: theme.spacing(3),
paddingTop: theme.spacing(3)
}
}));
const LoginView = () => {
const classes = useStyles();
const navigate = useNavigate();
return (
<Page className={classes.root} title="Login">
<Box
display="flex"
flexDirection="column"
height="100%"
justifyContent="center"
>
<Container maxWidth="sm">
<Formik
initialValues={{
email: 'demo@devias.io',
password: 'Password123'
}}
validationSchema={Yup.object().shape({
email: Yup.string()
.email('Must be a valid email')
.max(255)
.required('Email is required'),
password: Yup.string()
.max(255)
.required('Password is required')
})}
onSubmit={() => {
navigate('/app/dashboard', { replace: true });
}}
>
{({
errors,
handleBlur,
handleChange,
handleSubmit,
isSubmitting,
touched,
values
}) => (
<form onSubmit={handleSubmit}>
<Box mb={3}>
<Typography color="textPrimary" variant="h2">
Sign in
</Typography>
<Typography
color="textSecondary"
gutterBottom
variant="body2"
>
Sign in on the internal platform
</Typography>
</Box>
<Grid container spacing={3}>
<Grid item xs={12} md={6}>
<Button
color="primary"
fullWidth
startIcon={<FacebookIcon />}
onClick={handleSubmit}
size="large"
variant="contained"
>
Login with Facebook
</Button>
</Grid>
<Grid item xs={12} md={6}>
<Button
fullWidth
startIcon={<GoogleIcon />}
onClick={handleSubmit}
size="large"
variant="contained"
>
Login with Google
</Button>
</Grid>
</Grid>
<Box mt={3} mb={1}>
<Typography
align="center"
color="textSecondary"
variant="body1"
>
or login with email address
</Typography>
</Box>
<TextField
error={Boolean(touched.email && errors.email)}
fullWidth
helperText={touched.email && errors.email}
label="Email Address"
margin="normal"
name="email"
onBlur={handleBlur}
onChange={handleChange}
type="email"
value={values.email}
variant="outlined"
/>
<TextField
error={Boolean(touched.password && errors.password)}
fullWidth
helperText={touched.password && errors.password}
label="Password"
margin="normal"
name="password"
onBlur={handleBlur}
onChange={handleChange}
type="password"
value={values.password}
variant="outlined"
/>
<Box my={2}>
<Button
color="primary"
disabled={isSubmitting}
fullWidth
size="large"
type="submit"
variant="contained"
>
Sign in now
</Button>
</Box>
<Typography color="textSecondary" variant="body1">
Don't have an account?{' '}
<Link to="/register" variant="h6">
Sign up
</Link>
</Typography>
</form>
)}
</Formik>
</Container>
</Box>
</Page>
);
};
export default LoginView;
我做错了什么?
更新
这是 index.jsx:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import { FirebaseContext } from './firebase';
import store, { firebase } from './redux/store';
ReactDOM.render(
<FirebaseContext.Provider value={firebase}>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</FirebaseContext.Provider>,
document.getElementById('root'),
);
这是 App.jsx:
import React, { useEffect } from 'react';
import { AnimatePresence } from 'framer-motion';
import { connect } from 'react-redux';
import { compose } from 'recompose';
import { useRoutes } from 'react-router-dom';
import { ThemeContextProvider } from './theme/ThemeProvider';
import { getAlbumData } from './redux/albumData/albumData.actions';
import { getMetaData } from './redux/albumMetaData/albumMetaData.actions';
import { withAuthentication } from './session';
import './styles/index.css';
import routes from './routes';
const AnimatedSwitch = () => {
const routing = useRoutes(routes);
return (
<AnimatePresence exitBeforeEnter initial={false}>
<div>{routing}</div>
</AnimatePresence>
);
};
const App = props => {
const { getMeta, getAlbum } = props;
useEffect(() => {
getMeta();
getAlbum();
}, [getMeta, getAlbum]);
return <ThemeContextProvider> {AnimatedSwitch()} </ThemeContextProvider>;
};
const mapDispatchToProps = dispatch => ({
getMeta: () => dispatch(getMetaData()),
getAlbum: () => dispatch(getAlbumData()),
});
export default compose(connect(null, mapDispatchToProps), withAuthentication)(App);
(对不起,这是一个大应用程序)但到目前为止我只使用了const navigate = useNavigate();。我的意思是路由器的useNavigate(),效果很好,但现在Link我不明白
【问题讨论】:
-
@RobertTerrell v6
Route组件不使用exact属性。这是从 v5 到 v6 的 API 更改的一部分,默认情况下它们完全匹配。 -
您能否包含构建您的路线的组件,以便我们了解它是如何处理它们的? V6 现在做了很多相对路由,所以你可能不小心嵌套了一些东西或者没有正确指定链接路径。
-
我对基于对象的路由不是很熟悉,是不是需要引入 useRouter 钩子,如下所示reacttraining.com/blog/react-router-v6-pre
-
感谢我更新了我的 Q!
-
我想我解决了我确实喜欢这个
<Link component={RouterLink} to="../register",添加“../”以提升register所在的级别。我通过实验发现了这一点,文档中没有关于此的内容。对此的任何想法表示赞赏