简体   繁体   中英

react-router-dom and typescript not displaying the components

Not sure where I'm going wrong, I looked at other questions and it seems to be similar and still not working.

Clicking both home or collections displays the home component even if though the route changes. My collections component just has a simple <h1>hello collections</h1> which never gets displayed. Home always stays prevalent.

I have my app.tsx file:

import React from 'react';
import {Nav} from './layout/header/Nav';
import {Home} from './templates/home/Home';
import {Collections} from './templates/collections/Collections';
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";

import './App.scss';


const App: React.FC = () => {
  return (
        <Router>
            <Nav/>
            <div className="main-content">
                <div>
                    <Switch>
                        <Route exactly component={Home} pattern="/" />
                        <Route exactly component={Collections} pattern="/Collections" />
                    </Switch>
                </div>
            </div>

        </Router>
  );
}

export default App;

in which the Nav.tsx:

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

import './nav.scss';

export const Nav:React.SFC = () => (
        <nav>
            <ul>
                <li><Link to="/">Home</Link></li>
                <li><Link to="/Collection">Collection</Link></li>
            </ul>
        </nav>
)
<Route exactly component={Home} pattern="/" />

This should say <Route exact ... , not <Route exactly ... . Also it should say path="/" not pattern="/" (same for the other route). Since the route is not actually defined as exact , this means the Home component will always be shown (because every route will match with / ). So your routes should be:

<Switch>
    <Route exact component={Home} path="/" />
    <Route exact component={Collections} path="/Collections" />
</Switch>

Also there is a typo in your Collection route/link. The route is stated as:

<Route exactly component={Collections} pattern="/Collections" />

Collection s is plural. But in your Link, Collection is singular:

<li><Link to="/Collection">Collection</Link></li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM