简体   繁体   中英

Unable to pass props to component through react-router

I am unable to pass props using react-router. My code till now:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import 'normalize.css/normalize.css';
import './styles/styles.scss';

const EditExpensePage = props => {
  console.log(props);

  return <div>Editing the expense with id of </div>;
};

const AppRouter = () => {
  return (
    <BrowserRouter>
      <div>
        <Switch>
          <Route path="/edit/:id" component={EditExpensePage} />
        </Switch>
      </div>
    </BrowserRouter>
  );
};

ReactDOM.render(<AppRouter />, document.getElementById('appDiv'));

Error screenshot

错误截图

I am trying to access the id in console as simple as that.

The error is showing only when I am trying to pass props

path="/edit/:id"

Source Link: https://reacttraining.com/react-router/web/api/Route/route-props

This is the same problem as in this question . The problem is specific to the setup. As shown in error message, bundle.js is loaded from current path, /edit/bundle.js , while it should be loaded from /bundle.js .

Scripts should either have absolute paths:

<script type="text/javascript" src="/bundle.js"></script>

Or base URL should be specified:

<base href="/">

It may be an issue with your local environment, I dont see anyproblem with your code. I tried out in https://codesandbox.io/s/ox773ywmn9 and there is no issue

我可以使用以下方式访问子组件中的道具:

this.props.match.params.id

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