【问题标题】:how to define a react router's IndexRoute when using dynamic routing使用动态路由时如何定义反应路由器的IndexRoute
【发布时间】:2016-09-09 21:34:10
【问题描述】:

我拥有的是root route 定义:

const rootRoute = {
    childRoutes: [{
        path: '/',
        component: require('./screens/Container'),
        appGlobalVars: appGlobalVars,
        childRoutes: [
            require('./routes/ListApps'),
            require('./routes/Settings'),
            require('./routes/Profile')
        ]
    }]
};


var runApp = (appGlobalVars) => {
    var routes = (
        <Provider store={store}>
            <Router history={ history } routes={rootRoute} />
        </Provider>
    );

    render(routes, document.getElementById('app'));
};

还有一些带有嵌套动态路由的设置:

./routes/Settings/index.js:

module.exports = {
    path: 'settings',
    getComponent(nextState, cb) {
        require.ensure([], (require) => {
            cb(null, require('../../screens/AppSettings'))
        })
    },
    getChildRoutes(partialNextState, cb) {
        require.ensure([], (require) => {
            cb(null, [
                require('./General'),
                require('./Users')
            ])
        })
    },
};

/settings 是父组件,它渲染{this.props.children} react 路由器通行证。例如,如果我导航到/settings/general,我将渲染settings,然后将general 渲染为其子级:

./routes/Settings/General.js

module.exports = {
    path: 'general',
    getComponent(nextState, cb) {
        require.ensure([], (require) => {
            cb(null, require('../../screens/AppSettings/General'))
        })
    }
};

这没关系,但我想做的是定义默认子组件Settings 如果导航到/settings 应该呈现。

简而言之:有没有办法在使用动态路由时定义IndexRoute 之类的东西?

【问题讨论】:

  • 你试过getIndexRoute()吗?

标签: reactjs react-router react-routing


【解决方案1】:

【讨论】:

  • 链接不再可用,我在 React Router 文档中看不到任何参考。
  • @nacho_dh Link 现在在 react-router-dom。但我不明白这与这个问题有什么关系。
  • 实际上,indexRoute 需要一个看起来像 { component: MyComponent } 的路由对象,因为我意识到 getComponent 完全异步返回,所以我在 { } 中使用了 getComponent 方法,这解决了我的问题。
【解决方案2】:

由于方法 getIndexRoutes 已被弃用,我注意到 indexRoute 需要一个对象 { component: SomeCompoent },这是 getComponent 返回的对象的架构,因此我使用 getComponent 提供 indexRoute 如下:

export default (store) => ({
  path : 'shops',
  childRoutes: [ 
    EditShopRoute(store),
  ],
  component: EntityLayout, // this renders always
  indexRoute: { // this renders only when route matches exactly /shops
    getComponent (nextState, cb) {
     require.ensure([], (require) => {
      const Shops = require('./containers/ShopsContainer').default
      const reducerShop = require('./modules/shops').default
      injectReducer(store, { key: 'shops', reducer: reducerShop })

      cb(null, Shops)

    /* Webpack named bundle   */
  }, 'shops')
  } }

})

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 2017-05-18
    • 2023-04-11
    • 2021-02-05
    • 2021-02-22
    • 2016-12-28
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多