react-router-dom基本使用+3種傳參方式


//App.js
import { 
  BrowserRouter as Router,
  Route,
  Link,
} from "react-router-dom";
// 引入組件
import Home from "....";
import News from "...."
function App() {
  return (
    <Router>
      <Link to="/">首頁</Link>
      <Link to="/news">新聞</Link>
      <Route exact path="/" component={Home} />
      <Route path="/news" component={News} />   
    </Router>
  );
}
export defautl App;

如何傳遞參數(3種)

1、params傳參(動態路由)

特點:刷新頁面參數不消失,參數會在地址欄顯示

  • 路由配置
<Route path='/about/:id' component={About} />
  • 跳轉方式
  //傳遞參數可以拆分為對象寫法:{pathname:'/about/3'}
  //html:
  <Link to={'/about/3'}>點擊跳轉</Link>
  //js:
  this.props.history.push('/about/3')
  • 獲取值
this.props.match.params.id  // 3

2、query傳參

特點:刷新頁面參數消失,參數不會在地址欄顯示

  • 路由配置
<Route path='/about' component={About} />
  • 跳轉方式
  //html:
  <Link to={{pathname:'/about', query:{id:3}}}>點擊跳轉</Link>
  //js:
  this.props.history.push({pathname:'/about', query:{id:3}})
  • 獲取值
this.props.location.query.id  // 3

3、state傳參

特點:刷新頁面參數不消失,參數不會在地址欄顯示

  • 路由配置
<Route path='/about' component={About} />
  • 跳轉方式
  //html:
  <Link to={{pathname:'/about', state:{id:3}}}>點擊跳轉</Link>
  //js:
  this.props.history.push({pathname:'/about', state:{id:3}})
  • 獲取值
this.props.location.state.id  // 3


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM