我使用> Project | Position | Status
> ------: | -------: | :-----
> 2 | 1 | A
> 2 | 2 | B
> 3 | 1 | B
> 3 | 2 | B
,react
,react-router
,react-redux
创建了一个应用程序,并且具有以下结构:
connected-react-router
我的想法是执行以下应用流程:
- app
- admin
- category
- categoryList
- categoryAdd
但是由于某些原因,我看不到最后一个组件(/admin -> /admin/category -> /admin/category/add
)呈现。
代码(结尾是沙盒链接):
CategoryAdd
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Route, Switch, Link } from "react-router-dom";
import { ConnectedRouter } from "connected-react-router";
import configureStore, { history } from "./configureStore";
import AdminPage from "./AdminPage";
import Category from "./Category";
const store = configureStore(/* provide initial state if any */);
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<>
<Link to="/admin/category">Category</Link>
<Switch>
<Route exact path="/admin" component={AdminPage} />
<Route exact path="/admin/category" component={Category} />
</Switch>
</>
</ConnectedRouter>
</Provider>,
document.getElementById("root")
);
import React from "react";
import { Link } from "react-router-dom";
export default function AdminPage() {
return (
<div style={{ border: "1px solid black", margin: 20 }}>
<div>AdminPage</div>
<Link to="/admin/category">Catgory page link</Link>
</div>
);
}
import React from "react";
import { Route, Switch } from "react-router-dom";
import { withRouter } from "react-router-dom";
import CategoryList from "./CategoryList";
import CategoryAdd from "./CategoryAdd";
function Category() {
return (
<Switch>
<Route path={`/admin/category`} render={() => <CategoryList />} />
<Route path={`/admin/category/add`} render={() => <CategoryAdd />} />
</Switch>
);
}
export default withRouter(Category);
import React from "react";
import { Link } from "react-router-dom";
export default function CategoryList() {
return (
<div style={{ border: "1px solid black", margin: 20 }}>
CategoryTable <Link to="/admin/category/add">Add</Link>
</div>
);
}
答案 0 :(得分:1)
您使用的Switch
仅匹配一条路线,因此您在index.js
和Category
组件中选择的第二条路线将永远不会被渲染。
1)删除Switch
中的exact
组件和index.js
路线道具
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<>
<Link to="/admin/category">Category</Link>
<Route path="/admin" component={AdminPage} />
<Route path="/admin/category" component={Category} />
</>
</ConnectedRouter>
</Provider>,
document.getElementById("root")
);
2)删除Switch
中的Category
function Category() {
return (
<>
<Route path={`/admin/category`} render={() => <CategoryList />} />
<Route path={`/admin/category/add`} render={() => <CategoryAdd />} />
</>
);
}
这可以在您的代码沙箱中使用,但是CategoryAdd组件已损坏,因为您没有导入React
。因此,将其添加到第一行:
import React from 'react';
答案 1 :(得分:1)
那是因为您的exact
路线上的/admin/category
关键字:
<Route exact path="/admin/category" component={Category} />
这仅匹配/admin/category
,而不匹配/admin/category/add
。
不幸的是,删除exact
仅能解决您的第一个问题。
另一个是您使用Switch
。您应该删除Switch
中的Index.js
,因为一旦匹配了/admin/category
路由,它就不会与类别组件中的任何路由匹配。