例如新聞網(wǎng)站掖肋,有很多l(xiāng)ist頁面,除了具體的新聞標題和新聞內容等動態(tài)內容不同赏参,其他的頁面部分都相同志笼,這個時候怎樣配置路由和組件呢?
這個時候就要用到路由的參數(shù)功能把篓,增加一條包含參數(shù)的路由配置纫溃。在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
就是該路由的參數(shù)(param)紊浩。
那么,是如何將路由的數(shù)據(jù)傳遞給頁面組件的呢疗锐?
1坊谁、點擊相關鏈接時,就會觸發(fā)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)
...
})
};
.......
}
在生命周期函數(shù)componentDidMount
中口芍,可以通過this.props.params.uniquekey
來接收uniquekey參數(shù)值(這里的uniquekey
與path路徑中的:uniquekey
相對應),React Router 將路由的數(shù)據(jù)都通過props
傳遞給了頁面組件简珠,這樣就可以非常方便的訪問路由相關的數(shù)據(jù)了阶界。
再來看看/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膘融,后面?zhèn)髁藆niquekey參數(shù)