2017-08-14 8 views
0

Iamはreact-reduxでアプリをやっているのですが、私のreduxストアをページリフレッシュして、あらかじめ定義されたライブラリを使用しないようにしたいので、redux状態をローカル状態に設定し、API呼び出しをcomponentWillUnmount私はそれを行うことができませんでした。このacheiveする彼らのいずれかのapprochさ:react-reduxでページ更新時に関数を呼び出す方法は?

そして、私のコードは次のとおりです。

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

activeUserは私のReduxの状態であると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

あなたがする必要があるのは、storeをlocalStorageに保存し、ページが再び開かれます。主なアプリでできること –

答えて

0

あなたが基本的にやろうとしていることは、リロードの間にアプリの状態(ユーザーなど)を維持したいということです。

この効果を得るにはlocalStorage APIを使用できます。

私はここに1つの解決策を挙げます。

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)); 
    } 
    } 
} 

勿論、あなたは適切ストアを更新しますreceivedActiveUserアクションを作成する必要があります。

関連する問題