【问题标题】:Unable to pass props to component through react-router无法通过 react-router 将 props 传递给组件
【发布时间】:2019-03-10 04:31:05
【问题描述】:

我无法使用 react-router 传递道具。到目前为止我的代码:

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'));

错误截图

我正在尝试访问控制台中的 id,就这么简单。

只有在我尝试传递道具时才会显示错误

path="/edit/:id"

来源链接:https://reacttraining.com/react-router/web/api/Route/route-props

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

这与this question 中的问题相同。问题是特定于设置的。如错误消息所示,bundle.js 是从当前路径 /edit/bundle.js 加载的,而应该从 /bundle.js 加载。

脚本应该有绝对路径:

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

或应指定基本 URL:

<base href="/">

【讨论】:

    【解决方案2】:

    这可能是您本地环境的问题,我没有看到您的代码有任何问题。我在https://codesandbox.io/s/ox773ywmn9试了一下,没有问题

    【讨论】:

    • 谢谢。看起来像,但知道如何解决这个问题吗?
    【解决方案3】:

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

    this.props.match.params.id
    

    【讨论】:

    • 您能否更具体地说明这如何有助于回答 OP 的问题?
    猜你喜欢
    • 2017-09-14
    • 2015-12-30
    • 2017-02-13
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2017-03-18
    • 1970-01-01
    相关资源
    最近更新 更多