如何在 React 中显示默认视图?

Home我有一个具有三个不同路线的 React 站点,当用户进入该站点时,我希望它自动显示第一个路线,称为。这是我的代码App.js:


<Router>

  <Navigation />

  <Switch>

    <Route path="/hypstats" exact component={() => <Home />} />

    <Route path="/hypstats/auctions" exact component={() => <AuctionViewer />} />

    <Route path="/hypstats/bazaar" exact component={() => <BazaarViewer />} />

  </Switch>

</Router>

这是Navigation组件:


import React, { Component } from 'react';

import { Link } from 'react-router-dom';

import "../App.css"


function Navigation(props) {

    return (

        <div className="navbar">

            <Link className="navlink" to="/hypstats">HypStats</Link> 

            <Link className="navlink" to="/hypstats/auctions">Auctions</Link>

            <Link className="navlink" to="/hypstats/bazaar">Bazaar</Link>

        </div>

    )

}


export default Navigation;


红颜莎娜
浏览 97回答 3
3回答

慕妹3242003

要将任何视图设为默认视图,您可以将以下内容添加到导航中<Route path="/" exact component={() => <Home />} />或者你可以写如下:<Redirect from="/" to="/hypstats"}&nbsp; /><Router>&nbsp; &nbsp; <Navigation />&nbsp; &nbsp; &nbsp; &nbsp; <Switch>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route path="/hypstats" exact component={() => <Home />} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route path="/hypstats/auctions" exact component={() => <AuctionViewer />} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route path="/hypstats/bazaar" exact component={() => <BazaarViewer />} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; **<Route path="/" exact component={() => <Home />} />**&nbsp; &nbsp; &nbsp; &nbsp; </Switch></Router>

月关宝盒

我们使用 basename 属性来告诉站点的基本名称。/hypstats这样,在接下来的路由中,每次添加新路由时,我们就不必在此处手动设置基本名称。React Router 自己管理它。<Router basename="/hypstats">&nbsp; <Navigation />&nbsp; <Switch>&nbsp; &nbsp; <Route path="/" exact component={() => <Home />} />&nbsp; &nbsp; <Route path="/auctions" exact component={() => <AuctionViewer />} />&nbsp; &nbsp; <Route path="/bazaar" exact component={() => <BazaarViewer />} />&nbsp; </Switch></Router>

jeck猫

在您的应用程序组件中的某个位置运行它。history.push({ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pathname:&nbsp;'/hypstats', });您正在使用“react-router-dom”,因此您可以导入:import&nbsp;{&nbsp;useHistory&nbsp;}&nbsp;from&nbsp;"react-router-dom";然后你可以使用:const&nbsp;history&nbsp;=&nbsp;useHistory();因此,每当用户进入您的 React 应用程序时,它都会打开“/hypstats”。您可以在 useEffect 中执行此操作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript