Javascript 组件中的反应路由器抓取URL段

Javascript 组件中的反应路由器抓取URL段,javascript,reactjs,url,react-router,Javascript,Reactjs,Url,React Router,我在React中使用一个简单的路由器 <Router> <div> <Switch> <Route path="/" component={ Home } exact /> <Route path="/contact" component={ Contact } /> <Route path="/:slug

我在React中使用一个简单的路由器

  <Router>
    <div>                   
       <Switch>
         <Route path="/" component={ Home } exact /> 
         <Route path="/contact" component={ Contact } />   
         <Route path="/:slug" component={ Post } />                       
        </Switch> 
    </div>
  </Router>

我使用REST从一个博客中提取帖子,并为单个博客帖子提供了一个名为Post的路由器组件。任何与
home
contact
不匹配的路由都使用
post
组件


如何在Post组件中获取或传递路由slug/url段?例如,如果url段/slug是
/some blog post title
,我想检索它,如果存在,最好使用React Router函数/方法

您可以在
props.match.params
对象中获取参数。要获取
:slug
参数,您需要编写
props.match.params.slug

示例

class Post extends React.Component {
  componentDidMount() {
    this.getPost(this.props.match.params.slug);
  }

  componentDidUpdate(prevProps) {
    if (prevProps.match.params.slug !== this.props.match.params.slug) {
      this.getPost(this.props.match.params.slug);
    }
  }

  getPost = slug => {
    // ...
  };

  render() {
    return <h2>{this.props.match.params.slug}</h2>;
  }
}
class Post扩展了React.Component{
componentDidMount(){
this.getPost(this.props.match.params.slug);
}
componentDidUpdate(prevProps){
if(prevProps.match.params.slug!==this.props.match.params.slug){
this.getPost(this.props.match.params.slug);
}
}
getPost=slug=>{
// ...
};
render(){
返回{this.props.match.params.slug};
}
}

谢谢!这管用!唯一的问题是,如果将Post路由添加到具有特定组件的其他路由下面,则在路由器交换机中忽略Post路由。如果我把它加在它们上面,它会工作,但是下面的路线会被忽略。我试着添加了
精确的
,但没有任何区别。@CyberJunkie不客气!我不太明白。该开关确保在
开关
中仅呈现一条
路线
。由于
path=“/:slug”
用作所有路由的通配符,因此不能将例如
/contact
置于其下方,因为这将适合
/:slug
的内部。我将
/contact
置于通配符路由之上,并且正在渲染它,但当转到自定义/动态路径时,通配符路由不存在。我有一些带有特定组件的路径,比如
/contact
,还有一个组件用于通配符路径。我不知道如何使这两种方法都起作用。@CyberJunkie你在问题中所写的应该起作用。您可能有重复的
Router
组件,或者可能有其他原因导致该行为。如果这导致未定义,您可以使用HOC with Router,例如:
import{with Router}from“react Router dom”,然后,
const PostWithRouter=withRouter(Post)
This wuld允许您访问
This.props.match
属性