react-router與react-redux跳轉后保存store數據(基於"react-router": "^2.8.0")


1.router引入

import { Route, IndexRoute, Router, hashHistory, browserHistory } from 'react-router';
<Router routes={routes} history={browserHistory}/>

假設store結構如下,分別是主頁home,詳情頁detail,評論頁comment

{
    comment: {
        comments:[],
        leng:0
    }
    detail: {
        content: "xxx"
    }
    home: {
        loading: false,
        pos: 0,
        stories: []
    }
}

2.在主頁home跳到詳情頁detail時,在主頁實現獲取詳情頁的請求數據,並賦予store,這樣store就保留home,

//在home里面跳轉是觸發fetchDetailData
<Link to={ '/detail/'+item.id}  onClick={this.props.fetchDetailData.bind(this,item.id) }>

獲取完詳情數據后,這樣store數據就成以下結構 

{
    comment: {
        comments:[]
        leng:0
    }
    detail: {
        content:"xxx"
    }
    home: {
        loading:false
        pos:29228
        stories:Array(201)
    }
}

3.在詳情頁detail跳到評論頁comment時,在詳情頁detail實現獲取評論頁comment的請求數據,並賦予store,這樣store就保留home,detail的數據了

//在詳情頁detail里面跳轉是觸發fetchCommentData
<Link to={ '/comment/'+this.articleId}  onClick={this.props.fetchCommentData.bind(this, this.articleId) }>評論</Link>

獲取完評論數據后,這樣store數據就成以下結構 

{
    comment: {
        comments:Array(20)
        leng:20
    }
    detail: {
        content:"xxx"
    }
    home: {
        loading:false
        pos:29228
        stories:Array(201)
    }
}

4.這樣,當要返回是時還原狀態就可以從本地緩存的store里面取數據渲染。

//在返回主頁home時,在主頁做判斷,回到最初的最初點擊跳轉時的位置
componentDidMount () {
    if(this.props.stories.length === 0 ){
        this.props.fetchHomeData(this.s)
    }else{
        console.log(this.props.route.component.displayName)
        if(this.props.route.component.displayName == "Connect(Home)"){
            window.scrollTo(0,this.props.pos);
        }
        this.s()
    }
        
}


github地址:https://github.com/fengnovo/webpack-react/tree/master/simpleFetch

順便介紹一個好東西,MacDown,麥當勞,一款專門給mac用寫markdown的軟件工具,開源免費又好用

地址:http://macdown.uranusjr.com/


免責聲明!

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



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