我正在使用react-router-dom v4,并且很难通过传递参数的方式来实现路由器。
const routing = (
<Router>
<div>
<Route exact path="/" component={App} />
<Route exact path="/login" component={Login} />
<Route exact path="/app" component={Mainpage} />
<Route exact path="/app/documents" component={Documents} />
<Route exact path="/app/quizzes" component={Quizzes} />
<Route exact path="/app/new" component={Documents} />
</div>
</Router>
);
const Quizzes = ({match}) => (
<div>
<Switch>
<Route exact path="/app/quizzes" component={QuizzesInterface} />
<Route exact path="/app/quizzes/:id" component={QuizInterface} />
</Switch>
</div>
)
const QuizzesInterface = ({match}) => (
<div>
<Background />
<Interface status='quizzes' index={0}/>
</div>
)
const QuizInterface = ({match}) => {
return(
<div>
<Background />
<Interface status='quizzes' index={match.params.id}/>
</div>
)
}
当我测试localhost:3000 / app / quizzes时,QuizzesInterface加载正常,但是当我测试localhost:3000 / app / quizzes / 1时,例如,未达到QuizInterface。我在做什么错了?
答案 0 :(得分:1)
从QuizInterface删除返回
const QuizInterface = ({match}) => (
<div>
<Background />
<Interface status='quizzes' index={match.params.id}/>
</div>
)
答案 1 :(得分:1)
问题是,在您的应用程序中,到处都使用了完全相同的关键字,当您没有嵌套的路由时,它可以正常工作,但是一旦嵌套了路由,它就会引起问题。
如果您将测验路由配置为
<Route exact path="/app/quizzes" component={Quizzes} />
现在测验组件具有两条路线
<Switch>
<Route exact path="/app/quizzes" component={QuizzesInterface} />
<Route exact path="/app/quizzes/:id" component={QuizInterface} />
</Switch>
因此,当您的网址路径为/app/quizzes/1
时,它与exact path="/app/quizzes"
不匹配,因此不会呈现Quizzes
组件,这很明显,它包含的任何嵌套路由都不会t渲染
解决方案是不要将exact
用于具有嵌套路由的路由路径,而应使用Switch
并正确排序路由
const routing = (
<Router>
<Switch>
<Route path="/login" component={Login} />
<Route path="/app/documents" component={Documents} />
<Route path="/app/quizzes" component={Quizzes} />
<Route path="/app/new" component={Documents} />
<Route path="/app" component={Mainpage} />
<Route path="/" component={App} />
</Switch>
</Router>
);
const Quizzes = ({match}) => (
<div>
<Switch>
<Route path="/app/quizzes/:id" component={QuizInterface} />
<Route path="/app/quizzes" component={QuizzesInterface} />
</Switch>
</div>
)
PS 。您可以将
exact
关键字用于“路线”,但要确保它们不会 包含嵌套路线