我正在遵循一条路线,在React中为自己构建一个投资组合。到目前为止,我所做的一切都是有效的,除了我遇到的一个问题。
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about-me" component={About} />
<Route path="/contact" component={Contact} />
<Route path="/blog" component={Blog} />
<Route exact path="/portfolio/:slug" component={PortfolioDetail} />
<Route component={NoMatch} />
</Switch>
我让开关运行在我已知的插件中,并且我的NoMatch正在捕获不存在的链接,除非我放置了一个格式为localhost的链接:#/portfolio/non_existant_ link。
产品组合详细信息代码:
import React from "react";
export default function(props) {
return (
<div>
<h2>Portfolio Detail for {props.match.params.slug}</h2>
</div>
);
}
无匹配代码:
import React from "react";
import { Link } from 'react-router-dom';
export default function() {
return (
<div>
<h2>We couldn't find that page</h2>
<Link to="/">Return to homepage</Link>
</div>
);
}
教师使用的是较旧版本的react。我做错了什么?
发布于 2021-07-13 17:41:56
传递段塞的一种方法是使用路由的render()
。不过,可能还有更干净的方法,所以如果有人对此有答案,我很乐意看到!
<Route exact
path="/portfolio/:slug"
render={(props) => (<PortfolioDetail path={props.history.location.pathname} />)}
/>
另一种方法是这里描述的useParams
react挂钩:Using the useParams hook in react
发布于 2021-07-15 14:47:03
好吧,我想我已经弄明白了,所以我会输入对我有效的答案,因为我怀疑我是同一个人遇到这个问题。解决方案被证明是一个解决方案,我的兄弟(他正在学习这门课程,并让这部分发挥作用)告诉我试一试。它最初不工作,但我认为这与缓存错误有很大关系。您的路径和":slug“之间必须有一个空格,如下所示:
render() {
return (
<div className='container'>
<Router>
<div>
<NavigationContainer />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about-me" component={About} />
<Route path="/contact" component={Contact} />
<Route path="/blog" component={Blog} />
<Route exact path="/portfolio/ :slug" component={PortfolioDetail} />
<Route component={NoMatch} />
</Switch>
</div>
</Router>
</div>
);
}
当你遇到bug时,一定要检查你的缓存!这是一个初学者的错误,作为一个初学者,我已经做到了,所以你不应该这样做。
https://stackoverflow.com/questions/68366633
复制