2017-08-14 212 views
0

Iam在react-redux中做一個應用程序,我想在頁面刷新時保留我的redux商店,並且認爲不使用預定義的庫,因此我將redux狀態設置爲本地狀態,並使componentWillUnmount中的api調用恢復爲還原頁面刷新狀態。但我無法做到這一點。是他們的任何計算策略,以達致這:如何在react-redux中調用頁面刷新功能?

而且我的代碼是:

componentWillMount(){ 
    this.setState({ 
     activeUser:this.props.activeUser 
    }) 
} 
componentWillUnmount(){ 
    this.props.loginUser(this.state.activeUser.user); 
} 

activeUser是我的終極版狀態和this.props.loginUser()使得API call.And我嘗試使用事件處理程序爲:

componentDidMount(){ 
    window.addEventListener('onbeforeunload', this.saveStore) 
} 

componentWillUnmount(){ 
    window.removeEventListener('beforeunload', this.saveStore) 
} 

saveStore(){ 
    this.props.loginUser(this.state.activeUser.user); 
} 

但它沒有爲我工作。

+0

我不認爲你可以保持刷新狀態。您需要使用本地/會話存儲來存儲狀態,或者將您的狀態寫入json文件並從那裏恢復,並在刷新完成後恢復它。 – Umesh

+1

您需要做的是將商店保存在localStorage中,並在您的頁面再次打開。你可以在你的主應用程序中做到這一點 –

回答

0

我的理解是,你基本上試圖做的是,你想在重新加載之間保持你的應用程序狀態(用戶信息等)。

可以使用localStorage API來實現此效果。

我會在這裏給出一個可能的解決方案。

class App extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = {activeUser: null}; 
    } 

    componentWillMount() { 
    let activeUser = localStrorage.getItem("activeUser"); 
    if (activeUser) { 
     this.props.receivedActiveUser(JSON.parse(activeUser)); 
    } 
    } 

    componentWillReceiveProps(nextProps) { 
    this.setState(activeUser: nextProps.activeUser); 
    } 

    componentWillUnmount(){ 
    if (this.state.activeUser) { 
     localStorage.setItem("activeUser", JSON.stringify(this.state.activeUser)); 
    } 
    } 
} 

Ofcourse,你必須創建一個receivedActiveUser行動,這將相應地更新商店。

相關問題