无法通过反应路由器将道具传递给组件

编程入门 行业动态 更新时间:2024-10-21 09:42:14
本文介绍了无法通过反应路由器将道具传递给组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用 react-router 传递道具.我的代码到现在:

从'react'导入React;从 'react-dom' 导入 ReactDOM;从'react-router-dom'导入{ BrowserRouter, Route, Switch };导入'normalize.css/normalize.css';导入'./styles/styles.scss';const EditExpensePage = props =>{控制台日志(道具);返回<div>编辑id为</div>的费用;};const AppRouter = () =>{返回 (<浏览器路由器><div><开关><Route path="/edit/:id" component={EditExpensePage}/></开关>

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

错误截图

我试图在控制台中访问 id 就这么简单.

错误仅在我尝试传递道具时显示

path="/edit/:id"

源链接:https://reacttraining/react-路由器/web/api/Route/route-props

解决方案

这与 这个问题.该问题特定于设置.如错误信息所示,bundle.js是从当前路径/edit/bundle.js加载的,而应该从/bundle.js<加载/代码>.

脚本应该有绝对路径:

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

或应指定基本 URL:

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/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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 07:56:20,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由器   道具   组件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!