我在使用反应路由器时遇到问题。 在我的示例中,当路由 http://localhost:3000/ingredient-collection/刷新时,页面刷新正常,但是当路由 http://localhost:3000/ingredient-collection/cones 并且我刷新时,组件消失了。
这是我第一次使用反应路由器,所以你能帮帮我吗
这是我的应用程序.js:
return (
<Router>
<MuiThemeProvider theme={theme}>
<Provider store={store}>
<div className={classes.minSize}>
<div className='mobileNavBar'>
<NavBarMobile
handleClick={this.handleClick} />
</div>
<div className='desktopNavBar'>
<NavBarDesktop />
</div>
<MenuBar
menuAnimation={menuAnimation}
handleClick={this.handleClick}
/>
<BackDrop
menuAnimation={this.state.setOpen}
handleClick={this.handleClick}
/>
<Switch>
<Route exact path="/"><GerHome /></Route>
<Route exact path="/machine-collection"><GerMachineCollection /></Route>
<Route exact path="/ingredient-collection"><GerIngredientPageRouter /></Route>
<Route exact path="/enquiry-collection"><GerEquipmentPageRouter /></Route>
<Route exact path="/enquiry-form"><EnquiryForm /></Route>
<Route exact path="/contact-form"><ContactForm /></Route>
</Switch>
<FooterBar style={{ position: 'fixed', bottom: '0' }} />
</div>
</Provider>
</MuiThemeProvider>
</Router>
);
}
这是GerIngredientsPageRouter.js:
const GerIngredientPageRouter = () => {
let { path, url } = useRouteMatch();
return (
<Router>
<div className="PageRouterBackground">
<span className="MainRouterHeader">Zutaten</span>
<AppBar position="static" className="RouterMenu">
<div className="TabRouterContainer">
<Tab
label="Saucen"
className="TabProdRouterIngredients"
component={Link}
exact to={`${url}`} />
<Tab
label="Waffelbecher/-hörnchen"
className="TabProdRouterIngredients"
component={Link}
exact to={`${url}/cones`} />
<Tab
label="Toppings"
className="TabProdRouterIngredients"
component={Link}
exact to={`${url}/toppings`} />
<Tab
label="Fertigmix"
className="TabProdRouterIngredients"
component={Link}
exact to={`${url}/mix`} />
<Tab
label="Pulver"
className="TabProdRouterIngredients"
component={Link}
exact to={`${url}/powder`} />
</div>
</AppBar>
<Switch>
<Route exact path={`${path}`}>
<GerSyrupsColPage />
</Route>
<Route path={`${path}/cones`}>
<GerConesColPage style={{ margin: '0' }} />
</Route>
<Route path={`${path}/toppings`}>
<GerToppingsColPage />
</Route>
<Route path={`${path}/mix`}>
<GerMixColPage />
</Route>
<Route path={`${path}/powder`}>
<GerPowderColPage />
</Route>
</Switch>
</div>
</Router>
)
}
这是因为您的路线exact
道具设置为true
。这意味着GerIngredientPageRouter
只有在location.pathname
/ingredient-collection
时才会渲染。只需删除exact
,路由将匹配:
<Route path="/ingredient-collection"><GerIngredientPageRouter /></Route>
您的路由组件path
与Tabs
中指定的组件不匹配。
使用从useRouteMatch
中提取的url
而不是path
。
例如:
<Route exact path={`${url}`}>
<GerSyrupsColPage />
</Route>
<Route path={`${url}/cones`}>
<GerConesColPage style={{ margin: '0' }} />
</Route>
尝试将package.json中的react-router-dom
版本更改为"react-router-dom": "^5.2.0",
,然后运行npm install
(如果您使用的是npm(或yarn
(如果您使用的是yarn(