我试图弄清楚启用HMR并遇到以下错误时,React-router在AppContainer中的工作方式。您能解释一下骇客发生了什么吗?


  不变违反:根路径必须呈现单个元素


Index.js

import React from 'react';
import ReactDOM from 'react-dom';

import { AppContainer } from 'react-hot-loader';
// AppContainer is a necessary wrapper component for HMR

import Routes from './routes/index';
const MOUNT_APP = document.getElementById('root');

const render = () => {
  ReactDOM.render(
    <AppContainer>
      <Routes />
    </AppContainer>,
    MOUNT_APP
  );
};

render();

// Hot Module Replacement API
if (module.hot) {
  module.hot.accept('./routes/index', () => {
    render()
  });
}


路由文件为:

import React from 'react';
import { Router, IndexRoute, browserHistory } from 'react-router';

import Home from './Home';
import SubView from './Sub';

const componentRoutes = {
  component   : Home,
  path        : '/',
  indexRoute  : SubView,
  childRoutes : [

  ]
}

const Routes = () => {
  return (
    <Router history={browserHistory} routes={componentRoutes} />
  );
};

export default Routes;


HomeView组件:

import React from 'react';

const HomeView = () => {
    <div>
      <h4>Welcome</h4>
    </div>
}

export default HomeView;


HomeView路线:

import HomeView from './components/SubView';

export default {
  component: HomeView
}


附注:SubView等于HomeView。

最佳答案

您需要从组件返回一个元素。现在,您的HomeView组件如下所示:

const HomeView = () => {
    <div>
      <h4>Welcome</h4>
    </div>
}


您需要返回标记,而不是像这样将其放入函数主体中:

const HomeView = () => {
    return (
         <div>
             <h4>Welcome</h4>
         </div>
    )
}

07-25 23:13