我正在使用React Router v5,每次导航时都会刷新整个页面。
我正在使用react-router-dom
Link
组件
我正在做一些服务器端渲染,但这不会影响页面加载到浏览器后导航的工作方式,对吗?
这是我主要的客户入口点:
ReactDOM.hydrate(
<Provider store={store}>
<BrowserRouter>
<StylesProvider generateClassName={generateClassName}>
<ThemeProvider theme={theme}>
<MuiPickersUtilsProvider utils={MomentUtils}>
<ApiProvider value={api}>
<App persistor={persistor} />
</ApiProvider>
</MuiPickersUtilsProvider>
</ThemeProvider>
</StylesProvider>
</BrowserRouter>
</Provider>,
document.querySelector('#root')
)
这是我的 App 组件,它在进行路由:
export default function App(appProps: any) {
return (
<React.Fragment>
<SnackbarProvider maxSnack={3}>
<Switch>
{routes.map(({ path, exact, loginRequired, name, loadData, component: C }) => {
return (
<Route
key={path}
path={path}
exact={exact}
component={(props: RouteComponentProps) => {
return (
<PersistGate persistor={appProps.persistor}>
withLogin(<C {...props} />)
</PersistGate>
)
}}
/>
)
})}
</Switch>
</SnackbarProvider>
</React.Fragment>
)
}
每单击一次链接,我就会在服务器中看到一个新的GET请求。到目前为止,这还不是问题。但是现在我想嵌套一些路由,刷新整个页面确实成为一个问题。
这是我目前正在处理的(路径 /教程):
function TutorialPage(props: TutorialPageProps) {
const { classes, match } = props
const [state, setState] = React.useState("this state should persist when users navigate through the tutorial, since the parent url is not changing")
return (
<React.Fragment>
<div className={classes.main}>
<div className={classes.tutorialBanner} />
<div className={classes.tutorialContainer}>
<ul>
<li><Link to={`${match.url}/start`}>START</Link></li>
<li><Link to={`${match.url}/step-2`}>USER</Link></li>
<li><Link to={`${match.url}/step-3`}>ORG</Link></li>
</ul>
<Route path={`${match.url}/step-1`} render={() => <h1 onClick={() => setState("step one")}>Step One</h1>} />
<Route path={`${match.url}/step-2`} render={() => <h1 onClick={() => setState("step two")>Step two, should not reload the whole page!</h1>} />
<Route path={`${match.url}/step-3`} render={() => <h1 onClick={() => setState("step three")>Step three!</h1>} />
</div>
</div>
</React.Fragment>
)
}
const stateToProps = (state: AppState) => {
return { auth: state.auth }
}
const dispatchToProps = (dispatch: any) => ({})
export default connect(
stateToProps,
dispatchToProps
)(withStyles(styles)(TutorialPage))