困惑于编写反应路由器代码

时间:2016-02-01 20:57:51

标签: reactjs react-router

以不同的方式编写react-router有什么区别?

1。)如在react-router github页面中所见

  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="about" component={About}/>
      <Route path="users" component={Users}>
        <Route path="/user/:userId" component={User}/>
      </Route>
      <Route path="*" component={NoMatch}/>
    </Route>
  </Router>

2。)webpack code for hugeapp

import TodoApp from './TodoApp';
import TodoMain from './TodoMain';

export default {
  path: '/',
  component: TodoApp,
  indexRoute: { component: TodoMain },
  childRoutes: []
};

3。)webpack for simple app

import { Route, IndexRoute } from 'react-router';

import TodoApp from './TodoApp';
import TodoMain from './TodoMain';

export default (
  <Route path="/" component={TodoApp}>
    <IndexRoute component={TodoMain} />
  </Route>
);

1 个答案:

答案 0 :(得分:1)

只需查看官方文档的Alternate Configuration部分即可。它解释了react-router可以接受JSX或普通对象,每个都有两个强制属性:pathcomponent。该普通对象的indexRoute属性被替换为&#34; (实际上,它不是)由<IndexRoute />组成部分;并且childRoutes与组件的children prop相同,该组件由封装到组件中的任何内容填充。

所以,

export default {
  path: '/',
  component: TodoApp,
  indexRoute: { component: TodoMain },
  childRoutes: []
};

配置可以用JSX方式编写:

export default (
  <Route path="/" component={TodoApp}>
    <IndexRoute component={TodoMain} />
  </Route>
);