Javascript 在React中呈现标题组件后,如何重定向到主页?
我创建了一个“标题”,它从后端应用程序获取所有菜单及其内容 Header.jsJavascript 在React中呈现标题组件后,如何重定向到主页?,javascript,reactjs,react-router,Javascript,Reactjs,React Router,我创建了一个“标题”,它从后端应用程序获取所有菜单及其内容 Header.js {getMenus.map(getMenu => ( <Button key={getMenu.name} variant="text" color="inherit" > <Link style={{
{getMenus.map(getMenu => (
<Button
key={getMenu.name}
variant="text"
color="inherit"
>
<Link
style={{ textDecoration: "none", color: "white" }}
// to={getMenu.link}
to={getMenu.link.concat(
getMenu.link === "/" ? "" : "/",
getMenu.id
)}
>
{getMenu.name}
</Link>
</Button>
))}
<Router>
<div className="App">
<Header />
<Switch>
<Route path="/:id" exact component={Home} />
<Route path="/hello/:id" exact component={Hello} />
<Switch>
<Footer>
</div>
</Router>
{getMenus.map(getMenu=>(
{getMenu.name}
))}
getMenus是菜单列表,将显示在标题中。我使用了react router来显示菜单的相关内容
App.js
{getMenus.map(getMenu => (
<Button
key={getMenu.name}
variant="text"
color="inherit"
>
<Link
style={{ textDecoration: "none", color: "white" }}
// to={getMenu.link}
to={getMenu.link.concat(
getMenu.link === "/" ? "" : "/",
getMenu.id
)}
>
{getMenu.name}
</Link>
</Button>
))}
<Router>
<div className="App">
<Header />
<Switch>
<Route path="/:id" exact component={Home} />
<Route path="/hello/:id" exact component={Hello} />
<Switch>
<Footer>
</div>
</Router>
当我启动我的反应应用程序时,我看到中间部分的空白,因为我没有点击任何菜单。
在Header.js中,一旦API调用完成,调用
this.props.history.push('/Home/{id}')
,以从调用中加载带有id的页面
基于类的组件中的示例:
class MyComp extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
apiCall().then(id => {
this.props.history.push('/hello/' + id);
})
}
render() {
return(
null
);
}
}
进一步阅读props.history
在Header.js中,API调用完成后,调用
this.props.history.push('/home/{id}')
加载带有调用id的页面
基于类的组件中的示例:
class MyComp extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
apiCall().then(id => {
this.props.history.push('/hello/' + id);
})
}
render() {
return(
null
);
}
}
进一步阅读props.history
也有助于提供动态ID
< Redirect to={`/hello/${id}`} />
也有助于提供动态ID < Redirect to={`/hello/${id}`} />
请详细说明历史。推送()或指向我的博客或视频。我是新来的反应者。你能详细说明一下历史吗。推送()或指向我的博客或视频。我是新手。我希望在应用程序首次启动时呈现主组件,路径为“/4”类似的内容。我希望在应用程序首次启动时呈现主组件,路径为“/4”类似的内容