简体   繁体   中英

Facing difficulty with configuring dynamic url params using react-router

I am trying to create dynamic URLs to render different content based on URL params .

When I use:

<Route path="/example/:id" component={Example} />

and then if I go to /example/99 on my browser, I am getting an error message on the console that says:

GET http://localhost:8080/example/bundle.js net::ERR_ABORTED 404 (Not Found)

However, when I remove the forward slash before the param then it works fine. Eg when I use:

<Route path="/example:id" component={Example} />

and then if I fo to /example99 on my browser, I am getting the expected results.

How do I solve this, given I want to use / while routing to different ids?

PFB the entire Routes.js file content. Everything works fine until I add / before :id

import React from "react";
import { BrowserRouter, Route, Switch, Link, NavLink } from "react-router-dom";
import ExpenseDashboardPage from "../components/ExpenseDashboardPage";
import AddExpensePage from "../components/AddExpensePage";
import EditExpensePage from "../components/EditExpensePage";
import HelpPage from "../components/HelpPage";
import NotFoundPage from "../components/NotFoundPage";
import Header from "../components/Header";

const AppRouter = () => (
    <BrowserRouter>
        <div>
            <Header />
            <Switch>
                <Route path="/" component={ExpenseDashboardPage} exact={true} />
                <Route path="/create" component={AddExpensePage} exact={true} />
                <Route path="/edit:id" component={EditExpensePage} />
                <Route path="/help" component={HelpPage} exact={true} />
                <Route component={NotFoundPage} />
            </Switch>
        </div>
    </BrowserRouter>
);

export default AppRouter;

Not sure why, but rolling back to react-router-dom@4.1.2 fixed this for me.

I was getting the same problem while learning Andrew Mead React JS class. By the way I fix this problem by using ":" instead of "/" . I really don't know exactly what is the problem. But I fix this here is the code:

Before Problem:

<Route path="/edit/id" component={EditExpansepage} />

I solve this by using this line:

<Route path="/edit:id" component={EditExpansepage} />

and from browser I sending this URL:

http://localhost:8080/edit:99

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