首页 > 解决方案 > 从另一个组件访问时,reactjs 中的注销功能不起作用

问题描述

我正在使用 ReactJs 在一个简单的电子商务网站中添加产品组件。从登录页面单击注销时,它工作正常。但是当访问添加产品组件时,我试图从那里退出,然后我面临以下问题。我们正在尝试在本地存储中添加用户详细信息并获取它们以将电子邮件属性添加到产品详细信息对象。

index.js

<Col >
   <span className="nav-link btn" onClick={logout} style={{color: 'white'}}>SignOut</span>
</Col>

const logout = () => {
    console.log("hellooooooooooo")
    dispatch(signout())
}

Authaction.js

export const signout = () => {

return async dispatch => {
    dispatch({ type: authConstants.LOGOUT_REQUEST });
    console.log("entered signout method")
    const res = await axios.post('/admin/signout');
    console.log("response"+res)

    if(res.status === 200){
        
        console.log("Signout check in if condition")
        localStorage.clear();
        console.log("hello world.....cleared local storage")
        dispatch({ type: authConstants.LOGOUT_SUCCESS });
        window.location = "/"
    }else{
        dispatch({
            type: authConstants.LOGOUT_FAILURE,
            payload: { error: res.data.error }
        });
        console.log("logout success")
        
        window.location = "/"
    }
    
}
}

FarmerProductDisplay.js

This JS file is getting rendered while clicking on signout and the below code is throwing the exception.

const user=localStorage.getItem('user')
const ema=JSON.parse(user).email

由于我们正在清除 Authaction.js 中的存储,我们无法从中获取 FarmerProductDisplay.js 中的用户详细信息等电子邮件属性。我们收到以下错误。

 TypeError: Cannot read property 'email' of null
 FProduct
 C:/Users/hbkes/Desktop/FCC/Front/src/components/products/FProduct.js:21
  18 |    }
  19 |    const user=localStorage.getItem('user')
  20 |    console.log("user"+user)
> 21 |    const ema=JSON.parse(user).email
     | ^  22 |    console.log("email"+ema)
  23 | 
  24 |  return(

您能否帮助建议从其他来源而不是本地存储获取用户详细信息的替代解决方案?请注意,FarmerProductDisplay.js 是一个不同的组件。

标签: javascriptpythonreactjsreact-reduxe-commerce

解决方案


推荐阅读