React路由器动态路由不呈现组件 [英] React router dynamic routes not rendering component

查看:498
本文介绍了React路由器动态路由不呈现组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过以下示例来使路由器动态路由反应起作用: https://github.com/rackt/react-router/tree/master/examples/huge-apps

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

这是我的设置:

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

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

import React from 'react';

console.log('testing');

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

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>

当我运行服务器时,我看到 Hello 显示在 index.html ,我还看到 console.log('testing')来自 App.js ,但实际的 App.js 组件不会呈现。有什么想法吗?

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. Any ideas why?

谢谢!

编辑:
如果我在下面将 ./ components / App.js 更改为ES5语法,它可以正常工作!这是为什么?反应路由器的组件:require('./ components / App')不适用于ES6?

If I change ./components/App.js to ES5 syntax below, it works! Why is that? Does react router's component: require('./components/App') not work with ES6?

var React = require('react');

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

module.exports = App;


推荐答案

我想,你使用的是Babel 6,他们在哪里已更改 commonjs 需要语法。

I think, you are using Babel 6, where they changed commonjs require syntax.

现在,您需要添加默认

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

I有同样的问题,终于找到了如何使它工作。

I had the same problem, finally found how to make it work.

这篇关于React路由器动态路由不呈现组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆