简体   繁体   English

Reactjs redux存储页面刷新状态。 componentWillUnmount无法正常工作

[英]Reactjs redux store state on page refresh. componentWillUnmount not working

I have a component like: 我有一个组件,如:

import React, { PropTypes, Component } from 'react'


class MyView extends Component {

    render() {

        return (
            <div>
                Something
            </div>
        )
    }
    componentWillUnmount() {
        console.log("Hellooww world")
        actions.store_state() 
    }

}

export default MyView

Here when I refresh the page I want to call actions.store_state() funciton. 在这里,当我刷新页面时,我想调用actions.store_state()函数。

But when I refresh the page componentWillUnmount() is not called. 但是当我刷新页面componentWillUnmount()没有被调用。 How can I call any function or store the state to localStorage when page is refreshed. 刷新页面时,如何调用任何函数或将状态存储到localStorage。

To expand on @Maxx answer: 要扩展@Maxx答案:

import React, { PropTypes, Component } from 'react'


class MyView extends Component {

    render() {

        return (
            <div>
                Something
            </div>
        )
    }

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

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

    saveStore = (e) => {
        actions.store_state() 
    }

}

export default MyView

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM