如何使用react-router引导组件

时间:2016-05-18 21:29:30

标签: reactjs react-router

我遇到了一个问题,我的React组件没有被引导到页面中,但没有出现错误消息,所以我不知道发生了什么。我不相信问题出在CalcList.js或Calculator.js文件中,因为我已经能够在单页(即不使用react-router)上下文中呈现它们而没有任何问题

使用下面的index.js和App.js父项实现,当我访问时,我只是得到一个空页面而没有来自控制台的任何反馈。

index.js

import React from 'react';
import {render} from 'react-dom';
import {Router, Route, Link, IndexRoute, browserHistory} from 'react-router';
import App from './App';
import {Calculator} from './Calculator';
import {CalcList} from './CalcList';

render ((
    <Router history={browserHistory}>
      <Route path="/" component={App}>
        <IndexRoute component={CalcList} />
        <Route path="/calculator/:num" component={Calculator} />
      </Route>
    </Router>
), document.getElementById('root'));

App.js

import React, { Component } from 'react';
import {render} from 'react-dom';
import {Router, Route, IndexRoute, hashHistory} from 'react-router';
import CalcList from './CalcList';
import Calculator from './Calculator';

export default class App extends Component {
  render() {
    var children = React.Children.map(this.props.children, function(child) {
        return React.cloneElement(child);
    });
    return (
        <div id="app">
        {children}
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您已经在组件中定义了默认导出,因此index.js中的以下行不正确:

import {Calculator} from './Calculator';
import {CalcList} from './CalcList';

改为:

import Calculator from './Calculator';
import CalcList from './CalcList';

或者,您可以创建一个导出这些组件的对象:

components.js:

import Calculator from './Calculator';
import CalcList from './CalcList';

export {
    Calculator, 
    CalcList
}

然后你的原始导入就像这样:

import { Calculator, CalcList } from './components';