代码之家  ›  专栏  ›  技术社区  ›  Emixam23

React路由器引导和导航栏重定向

  •  1
  • Emixam23  · 技术社区  · 7 年前

    我今天和昨天读了很多书,我完全陷入了发展的泥潭。为了学会反应。Js,我正在制作一个简单的网站,按类别显示图片和描述。我面临的问题是我的导航项(导航栏)和重定向之间的链接。

    我的索引中有这个路由器。js公司:

    render((
        <Router history={hashHistory}>
          <Route path="/" component={App}>
            <IndexRedirect to="/index" />
            <Route path="/index" component={Home}/>
            <Route path="/dogs" component={Dogs}/>
            <Route path="/cats" component={Cats}/>
          </Route>
        </Router>
      ), document.getElementById('app'))
    

    import React from 'react'
    import { 
        Navbar as BoostrapNavBar,
        Nav,
        NavItem,
        MenuItem,
        NavDropdown,
        Jumbotron, 
        Button } from 'react-bootstrap';
    import { LinkContainer } from 'react-router-bootstrap';
    
    export default class Navbar extends React.Component {
        render () {
            return (
                <BoostrapNavBar inverse collapseOnSelect>
                    <BoostrapNavBar.Header>
                        <BoostrapNavBar.Brand>
                            <a href="#">{this.props.navbar_title}</a>
                        </BoostrapNavBar.Brand>
                        <BoostrapNavBar.Toggle />
                    </BoostrapNavBar.Header>
                    <BoostrapNavBar.Collapse>
                        <Nav pullRight>
                            <NavItem href="/dogs">Dogs</NavItem> 
                            <NavItem href="/cats">Cats</NavItem> 
                        </Nav> 
                    </BoostrapNavBar.Collapse>
                </BoostrapNavBar>
            );
        }
    }
    

    因此,我的站点呈现,但如果单击其中一个导航项,则会显示一条消息: Cannot GET /dogs .

    所以,我开始在互联网上搜索navbar如何与react路由器和。。。我得到了这么多答案,但我不能让它工作,我不明白为什么。我试过了 LinkContainer 但历史有问题,所以我检查了一下 Router 在索引中。js没有任何成功。

    我读了一些关于 <Switch> , <Browser> 等,但同样没有成功:(有什么想法吗?

    谢谢你的帮助

    1 回复  |  直到 7 年前
        1
  •  2
  •   Emixam23    7 年前

    你能这样做吗?

    import { Link } from 'react-router-dom';
    import { NavBar, Nav, NavItem} from 'react-bootstrap';
    

    ...

    <Nav>
        <NavItem componentClass={Link} href="/dogs" to="/dogs" active={location.pathname === '/dogs'}>Dogs</NavItem>
        <NavItem componentClass={Link} href="/cats" to="/cats" active={location.pathname === '/cats'}>Cats</NavItem>
    </Nav>
    

    获取自 here