接下來 我們來看看路由跳轉
先打開 我們Dva項目然后我們需要在routes 下創(chuàng)建一個自己的路由,如果您尚未掌握在Dva項目中創(chuàng)建路由,可以參考我的文章 React 在Dva項目中修改路由配置,并創(chuàng)建一個自己的路由
然后 我的項目有兩個路由 router.js代碼如下
一個 / 一個 /ProductPage
其實跳轉路由的方式很多 第一種 Link
然后 我們在首頁 / 下這樣寫
import { Link } from "dva/router";
這里 我們引入了Link組件 注意 這里 不再是router 而是 dva下的router 它做了一個封裝
然后在頁面上這樣寫
<Link to="/ProductPage">去ProductPage</Link>
使用這個Link組件 to指定要跳轉的路徑 /ProductPage
然后 我們運行項目
然后點擊我們寫的按鈕
這里 就已經完成了跳轉
但是 很多時候 我們希望在事件里面做跳轉
首先 我們函數方式的組件 需要在方法中接一下props參數
如果是 類 class 的組件 可以這樣 this.props 拿到
然后 我們外面聲明一個事件
const toProductPage = () => {
props.history.push("/ProductPage");
}
然后 頁面上面 我們可以寫個按鈕 來點擊調用這個函數
<Button onClick={ toProductPage } type="primary">Primary Button</Button>
運行項目
然后點擊我們綁定事件的按鈕 這樣就完成頁面的跳轉了
我們 還可以通過 routerRedux 來完成
首先 引入它
import { routerRedux } from "dva/router";
還是在dva幫我們封裝的router下面
然后 我們將之前的toProductPage改成這樣
const toProductPage = () => {
props.dispatch(routerRedux.push("/ProductPage"));
}
再次點擊 依舊能順利完成跳轉
還有一個比較特殊的東西
我們在src下的 components 目錄下創(chuàng)建一個 text.jsx
參考代碼如下
import React from "react"
export default class Product extends React.Component {
constructor(props){
super(props);
this.state = {
}
}
toProductPage = () => {
this.props.history.push("/ProductPage");
}
render(){
return (
<div>
<button onClick={ this.toProductPage }>Primary Button</button>
</div>
)
}
}
我們聲明了一個class類形式的組件 然后 在根組件中引入它
運行項目 之后 我們嘗試點擊按鈕
這里就報錯了 因為這個組件并不在路由包裹下
在路由包裹下的 這有這兩個組件
這時 我們可以通過withRouter來解決問題
我們將 text.jsx 代碼改成這樣文章來源:http://www.zghlxwxcb.cn/news/detail-604637.html
import React from "react"
import { withRouter } from "dva/router";
class Product extends React.Component {
constructor(props){
super(props);
this.state = {
}
}
toProductPage = () => {
this.props.history.push("/ProductPage");
}
render(){
return (
<div>
<button onClick={ this.toProductPage }>Primary Button</button>
</div>
)
}
}
export default withRouter(Product)
withRouter 也是在dva封裝的router中引入
然后 它是一個高階函數
我們再次運行項目
然后 點擊按鈕
我們的頁面跳轉就完成了文章來源地址http://www.zghlxwxcb.cn/news/detail-604637.html
到了這里,關于React Dva項目中路由跳轉的方法的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!