How to navigate to a new page react router v4

懵懂的女人 提交于 2019-12-04 18:20:26

You already had the imports in this.

import {
  BrowserRouter as Router,
  Link,
  Route
} from 'react-router-dom'

However, I would remove all of the routings in your CyptoList page and just make that CyptoList a component.

Now, you want to use those Links in your code to navigate between pages you need to make a place that you want to display the links in.

const Header = () => (
    <nav>
        <ul>
            <li><Link to='/'>CryptoList</Link></li>
            <li><Link to='/currency'>Currency</Link></li>
        </ul>
    </nav>
)

If in your CyptoList page you can just put the header in there like this <Header />

Now, the next part, the Router, you might want to make a new Router.js file or separate it. Or you could do something like this.

// Routes.js
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import CryptoList from './CryptoList';  // or whatever the location is
import Currency from './Currency'; // or whatever the location is

export default () => (
<BrowserRouter>
    <Switch>
      <Route exact path="/" component={CryptoList}/>
      <Route path="/currency" component={Currency}/>
    </Switch>
</BrowserRouter>
);

Then when you want to include your Routes as you saved it in the Routes.js file you can just do this.

import Routes from './Routes';

and use it by doing this...

<Routes />

You can always refer to this example on medium with a link to a CodeSandbox and CodePen. https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf

I encountered the same problem.

Your <Route /> is located in App.js. This is why every time you navigate to currency component you can still see original view in App.js.

Here is the solution:

You just need to move <Route /> to index.js not in App.js. Because in index.js there is nothing. when you navigate to <Currency /> you will go to a completely new page. You will never see views in App.js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!