简体   繁体   中英

Set up router with history in reactjs

I have 3 component and i want to make 2 button HOME and ABOUT (after click will redirect to page corresponding HOME (path '/') or ABOUT (path '/about'). Component NOTFOUND only show when path is wrong. But when i try to click HOME or ABOUT it always show NOTFOUND though the url has changed to '/' or '/about'. The details code is below, what must i do to make it work correctly. TKS all

import React, { useState } from 'react';
import {Router, Route, Switch} from 'react-router-dom'
import {createBrowserHistory} from 'history'

const history = createBrowserHistory()

function Home(props) {
    return (
        <div>Home</div>
    )
}

function AboutUs(props) {
    return (
        <div>About US</div>
    );
}
function NotFound(props) {
    return (
        <div>NotFound</div>
    );
}

function RouterDom(props) {
    
    const [count, setCount] = useState(1)
    
  
    return (
        <div>
            <div>
                <button onClick={() => history.push('/')}>Home</button>
                <button onClick={() => history.push('/about')}>About</button>
            </div>
            <div>
                <div>Count: {count}</div>
                <button onClick={() => setCount(count + 1)}>Add</button>
            </div>
            <Router history={history}>
                <Switch>
                    <Route exact path="/" component={Home} />
                    <Route path="/about" component={AboutUs} />
                    <Route component={NotFound}/>
                </Switch>
            </Router>
        </div>
    );
}

export default RouterDom;

You should use Link provided from react router dom instead of buttons.

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

<Link to="/">Home</Link>
<Link to="/about">About</Link>

You should also add path property to the Route tag:

<Route path="/about">
   <About />
</Route>

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