4

我无法让 React Router 中的 URL 参数功能正常工作,任何见解都会有所帮助!我尝试使用“react-router-dom”而不是“react-router”,但我得到了这个人得到的错误:https ://github.com/ReactTraining/react-router/issues/1799

当我执行 localhost:8000 时,该应用程序正常工作。当我转到 localhost:8000/123 时,浏览器按原样呈现index.html ,没有任何反应。Express 会干扰 React 吗?在 Express 中,我拥有以下内容:

app.get('*', function response(req, res) {
  res.write(middleware.fileSystem.readFileSync(path.join(__dirname, 'dist/index.html')));
  res.end();
});

这是我的main.js

import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import Routes from './shared/components/Routes';
const ROOT_ELEMENT = 'app';
ReactDOM.render((
   <Router history={browserHistory}>
   {Routes}
   </Router>
), document.getElementById(ROOT_ELEMENT));

我的routes.js

import { Route, IndexRoute, Link } from 'react-router';

import App from './App';
import HomePage from '../../pages/home/page';
import AboutPage from '../../pages/about/page';

const Child = ({ match }) => (
  <div>
    <h3>ID: {match.params.id}</h3>
  </div>
)

export default (
  <Route path="/" component={App}>
    <IndexRoute component={HomePage} />
    {/* <Route path="about" component={AboutPage} /> */}
    <Route path="/:id" component={Child} />
  </Route>
);

我的Home组件在不同的文件中定义如下(省略了所有导入和生命周期函数):

export default React.createClass({
  render: function() {
     {* bunch of JSX goes here *}
  }
});

根据要求,我的index.html文件:

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>Consent Form</title>
  <meta name="description" content="Privacy Consent Webform">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!--Google Material Design Icons-->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
  <div id="app"></div>
</body>
</html>

由于我的webpack 配置,html 没有捆绑作为脚本标记(捆绑已注入!)(以下代码只是配置的一部分):

entry: [
    'webpack-hot-middleware/client',
    'bootstrap-loader',
    path.join(__dirname, 'src/main.js')
  ],
  output: {
    path: path.join(__dirname, '/dist/'),
    filename: '[name].js',
    publicPath: '/'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.tpl.html',
      inject: 'body',
      filename: 'index.html'
    })
4

2 回答 2

1

当您向应用程序添加新路由时,您不能依赖热重载来注入新的路由+组件。我不得不 CTRL+C 并npm start再次运行。

这样就解决问题了!!

react-router-dom 也是一个 React Router v4 包,而 react-router 是一个旧版本。感谢@HalCarleton 指出这一点。我到处都看到了 react-router 的代码示例,而官方文档显示了 react-router-dom,我真的很困惑为什么会有两种不同类型的包。

于 2017-05-03T17:37:30.230 回答
1

尝试做这样的事情:

<Switch>
      <Route path="/auth/login/:token" render={props => <Login  {...this.props} {...props}/>}/>
      <Route path="/auth/login" component={Login}/>
   </Switch>

首先是带参数的路由,然后是不带参数的路由。在我的登录组件中,我console.log(props.match.params.token);对其进行了测试并为我工作。

于 2019-02-19T14:00:58.580 回答