如何在React App中分隔路线

时间:2019-01-18 13:27:16

标签: javascript reactjs react-router

我在index.js上有以下内容

<Router  routes={routes} />

I would like to have routes section in a separate file, so far I tried this:
routes.js

export default (
    <div>
        <Route path="/" component={AppComponent}>
            <Route path="/someother" component={AddProductComponent} />
        </Route>

        <Route path="/products" component={ListProductComponent} />
    </div>
);

和index.js

import routes from './routes';
<Router  routes={routes} />

由于某种原因,应用程序现在显示空白。好像没有渲染路线。

更新,这是我的整个index.js,除了由于stackoverflow伴有过多代码放置而缺少导入之外

const rootReducer = combineReducers({
    products: productReducer,
});

const store = createStore(
    rootReducer,
    applyMiddleware(thunk),
);

ReactDOM.render(
    <Provider store={store}>
        <Router  routes={routes} />
    </Provider>
    , document.getElementById('root')
);

更新routes.js

export default (
    <Switch>
       <Route exact path="/" component={AppComponent}/>

        <Route path="/products" component={ListProductComponent}>
            <Route path="/details/:productId" component={AddProductComponent} />
        </Route>
    </Switch>
);

1 个答案:

答案 0 :(得分:1)

您缺少开关:

<Switch>
    <Route path="/someother" component={AppComponent}>
    <Route path="/products" component={ListProductComponent} />
    <Route path="/" component={AppComponent}>
</Switch>

此外,您的代码将仅显示AppComponent,因为任何url(//home/etc)都以您在path属性中添加的斜杠开头。您可能希望将其作为最后一页,作为后备。

path属性适用于野生保健:path="/"-> path="/**"在功能上是相同的。如果您想要确切的路径,请在路线中添加exact


如果您打算将路由拆分为单独的文件,则可以执行以下操作:

<Switch>
    <Route path={"/user"} component={UserRouter}/>
    <Route path={"/product"} component={ProductRouter}/>
</Switch>
// In userRouter.jsx:
export function UserRouter() {
    return <Switch>
        <Route exact path={"/user/list"} component={UserListPage}/>
        <Route exact path={"/user/signup"} component={userSignupPage}/>
        <Route exact path={"/user/profile"} component={UserProfilePage}/>
    </Switch>
};