Javascript 反应:当用户关闭浏览器时删除cookie

Javascript 反应:当用户关闭浏览器时删除cookie,javascript,reactjs,cookies,react-cookie,Javascript,Reactjs,Cookies,React Cookie,我正在使用库react cookie(),我想在浏览器或选项卡关闭时删除用户cookie。我在Approuter中使用了ComponentWillUnmount,但当浏览器关闭时,这不起作用。有人知道如何做到这一点吗 import React from 'react'; import {Router, Route, Switch} from 'react-router-dom'; import history from '../data/history'; import { withCookie

我正在使用库react cookie(),我想在浏览器或选项卡关闭时删除用户cookie。我在Approuter中使用了ComponentWillUnmount,但当浏览器关闭时,这不起作用。有人知道如何做到这一点吗

import React from 'react';
import {Router, Route, Switch} from 'react-router-dom';
import history from '../data/history';
import { withCookies, Cookies } from 'react-cookie';
import { instanceOf } from 'prop-types';


class AppRouter extends React.Component{

static propTypes = {
    cookies: instanceOf(Cookies).isRequired
};


constructor(props){
    super(props)
}

componentWillMount(){
    const {cookies} = this.props;
    cookies.remove('userInfo');
}

render(){
    return(
        <Router history={history}>
            <div>
                <Header/>
                <div className="main-container">
                    <Switch>
                        //routes
                    </Switch>
                    <Footer/>
                </div> 
            </div>
        </Router>
    );
}
}

export default withCookies(AppRouter);
从“React”导入React;
从“react Router dom”导入{Router,Route,Switch};
从“../data/history”导入历史记录;
从“react cookie”导入{withCookies,Cookies};
从“道具类型”导入{instanceOf};
类批准器扩展了React.Component{
静态类型={
cookies:instanceOf(cookies)。需要
};
建造师(道具){
超级(道具)
}
组件willmount(){
const{cookies}=this.props;
cookies.remove('userInfo');
}
render(){
返回(
//路线
);
}
}
使用cookies导出默认值(AppRouter);

路由器确实收到cookies,为什么我不能用componentWillUnmount删除它?我该如何移除它们

不是真正的反应特异性,但您可以使用:

window.addEventListener(“卸载前”,ev)=>
{  
ev.preventDefault();
cookies.remove('userInfo');
});这可能会帮助您

componentDidMount(){
    window.addEventListener(
        "beforeunload",
        cookies.remove('userInfo')
    );
}
当您创建cookie时。 请将expires设置为0。 e、 g


浏览器关闭时,此cookie将过期。

如果删除过期日期,cookie不会被删除吗?AFAIK一个没有过期日期的cookie只在特定会话中有效。我的cookie没有过期数据@mirakuunwell,那么它应该在会话结束时过期。对不起,我的错。在tab close上没有看到您也要删除它。这个不适用于那种情况,是的。是的,没问题,@mirakurunt当浏览器完全关闭时,这个可以工作,但当标签关闭时就不行了。有什么建议吗?
cookies.set('userInfo', name, { expires: 0 });