0

我试图弄清楚当 HMR 启用并遇到以下错误时,react-router 如何在 AppContainer 内工作。你能解释一下黑客是怎么回事吗?

Invariant Violation:根路由必须渲染单个元素

索引.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;

主视图组件:

import React from 'react';

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

export default HomeView;

主页查看路线:

import HomeView from './components/SubView';

export default {
  component: HomeView
}

PS:SubView 等于 HomeView。

4

2 回答 2

2

您的HomeView组件不返回任何内容。您需要将内部 jsx 包装在return ( ... ).

于 2017-02-25T03:04:10.367 回答
2

您需要从组件中返回一个元素。现在你的组件HomeView看起来像这样:

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

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

const HomeView = () => {
    return (
         <div>
             <h4>Welcome</h4>
         </div>
    )
}
于 2017-02-25T03:07:49.980 回答