编程语言
首页 > 编程语言> > javascript – React路由器动态路由不呈现组件

javascript – React路由器动态路由不呈现组件

作者:互联网

我试图通过以下示例来使路由器动态路由反应起作用: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>

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

谢谢!

编辑:
如果我将./components/App.js更改为下面的ES5语法,它就可以了!这是为什么?反应路由器的组件:require(‘./ components / App’)是否与ES6不兼容?

var React = require('react');

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

module.exports = App;

解决方法:

我想,你使用的是Babel 6,它们需要语法才能使用changed.

现在,您需要添加默认值:

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

我有同样的问题,终于找到了如何让它工作.

标签:javascript,reactjs,react-router
来源: https://codeday.me/bug/20191006/1863349.html