简体   繁体   English

反应路由器动态路由不渲染组件

[英]React router dynamic routes not rendering component

I'm trying to get react router dynamic routing to work by following this example: https://github.com/rackt/react-router/tree/master/examples/huge-apps 我正在尝试通过以下示例使React Router动态路由正常工作: https : //github.com/rackt/react-router/tree/master/examples/huge-apps

Here's my setup: 这是我的设置:

webpack.config.js : webpack.config.js

module.exports = {
  devtool: 'inline-source-map',
  entry: './js/app.js',
  output: {
    path: '../public',
    filename: 'test-app.js',
    chunkFilename: '[id].chunk.js',
    publicPath: '/public/'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: [
            'es2015',
            'react'
          ]
        }
      }
    ]
  }

./js/app.js : ./js/app.js

import React from 'react';
import ReactDOM from 'react-dom';
import { createHistory, useBasename } from 'history';
import { Router } from 'react-router';

const history = useBasename(createHistory)({
  basename: '/'
});

const rootRoute = {
  component: 'div',
  childRoutes: [{
    path: '/',
    component: require('./components/App')
  }]
};

ReactDOM.render(
    <Router history={history} routes={rootRoute} />,
    document.getElementById('root')
);

./components/App.js : ./components/App.js

import React from 'react';

console.log('testing');

export default class App extends React.Component {
  render() {
    console.log('App');
    return (
        <div>
          App!
        </div>
    )
  }
}

index.html : index.html

<!doctype html>
<html>
    <head>
        <title>Test App</title>
    </head>
    <body>
        Hello
        <div id="root"></div>
        <script src="public/test-app.js"></script>
    </body>
</html>

When I run the server, I see Hello displayed from index.html , I also see console.log('testing') from App.js , but the actual App.js component does not render. 运行服务器时,我看到index.html显示了Hello ,也看到了App.js console.log('testing') ,但是实际的App.js组件未呈现。 Any ideas why? 有什么想法吗?

Thanks! 谢谢!

EDIT: If I change ./components/App.js to ES5 syntax below, it works! 编辑:如果我将./components/App.js更改为以下ES5语法,则可以使用! Why is that? 这是为什么? Does react router's component: require('./components/App') not work with ES6? 反应路由器的component: require('./components/App')不适用于ES6吗?

var React = require('react');

var App = React.createClass({
  render: function() {
    return (
      <div>
        App!
      </div>
    )
  }
});

module.exports = App;

I think, you are using Babel 6, where they changed commonjs require syntax. 我认为,您使用的是Babel 6,其中它们更改了 commonjs require语法。

Now, you need to add the default : 现在,您需要添加default

component: require('./components/App').default

I had the same problem, finally found how to make it work. 我遇到了同样的问题,终于找到了使它工作的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM