美文网首页
react如何在组件中获取路由参数?this.props.par

react如何在组件中获取路由参数?this.props.par

作者: 兔子不打地鼠打代码 | 来源:发表于2018-03-18 12:13 被阅读1330次

例如新闻网站,有很多list页面,除了具体的新闻标题和新闻内容等动态内容不同,其他的页面部分都相同,这个时候怎样配置路由和组件呢?

这个时候就要用到路由的参数功能,增加一条包含参数的路由配置。在root.js页面下进行设置。

【root.js】
import PCIndex from "./components/pc_index"
import PCNewsDetails from './components/pc_news_details';

<Router history={hashHistory}>
  <Route path="/" component={PCIndex}> </Route>
  <Route path="/details/:uniquekey" component={PCNewsDetails}> 
  </Route>
</Router>

注意,path属性中:uniquekey就是该路由的参数(param)。

那么,是如何将路由的数据传递给页面组件的呢?
1、点击相关链接时,就会触发path/details/:uniquekey,然后调用对应组件{PCNewsDetails}
2、组件内部

【pc_news_details.js】
class PCNewsDetails extends Component{
componentDidMount(){
        let myFetchOptions = {
            method:'GET'
        };
        fetch(
           "http://newsapi.gugujiankong.com/Handler.ashx?action=getnewsitem&uniquekey=" 
          + this.props.params.uniquekey , myFetchOptions)
          ...
            })
    };
.......
}
           

在生命周期函数componentDidMount中,可以通过this.props.params.uniquekey来接收uniquekey参数值(这里的uniquekey与path路径中的:uniquekey相对应),React Router 将路由的数据都通过props传递给了页面组件,这样就可以非常方便的访问路由相关的数据了。

再来看看/details来自哪里?

【pc_news_block.js】
class PCNewsBlock extends Component{
render(){
        const {news} = this.state;
        const newsList = news.length
            ? news.map((newsItem, index) =>(
                <li key={index}>
                    <Link to={'details/${newsItem.uniquekey}'} target="_blank"/>
                    {newsItem.title}
                </li>
            ))
            : "没有加载到任何新闻呢!";
}

跳转的地址为details,后面传了uniquekey参数

相关文章

网友评论

      本文标题:react如何在组件中获取路由参数?this.props.par

      本文链接:https://www.haomeiwen.com/subject/vmleqftx.html