[在Redux中获取用户个人资料时发生TypeError
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[在Redux中获取用户个人资料时发生TypeError相关的知识,希望对你有一定的参考价值。
[error log image 我已经遇到了这个问题,该问题目前对我不起作用
我基本上有一个可以注册和登录的身份验证应用,但是当我尝试获取配置文件数据时,我遇到了TypeError(无法读取未定义的属性'FirstName'。
在redux工具中
the isAuthenticated: true
error: null
and profile: {
joined: xxxxxx
_id:4rt43dfdsletc
firstName: "xxxx"
email:"adfadf@fsa.com"
}
等,一切都正常,并且该应用程序还包含redux持久性,也可以正常工作
但是,在导航栏中,我试图显示用户的名字,但出现错误
这是我的LOGIN.ACTION.JS
export const autUser = data => {
return async dispatch => {
// dispatch({ type: LOGIN_REQUEST}
return await apiLogin(data)
.then(res => {
const token = res.data.token;
console.log(token);
dispatch(success(token));
setAuthHeader(token);
dispatch(getUserProfile())
// console.log('User Details', jwt.decode(token));
})
//error will be dispatched here
.catch(err => console.log(err));
};
};
const success = token => {
localStorage.setItem(TOKEN_NAME, token);
return { type: LOGIN_SUCCESS };
};
const error = error => {
return { type: LOGIN_FAIL, payload: error };
};
在同一文件中获取配置文件
export const getUserProfile = () => {
return async dispatch => {
try {
console.log("fetching profile......")
const { data : {user} } = await apiFetchProfile();
dispatch({ type: PROFILE_FETCHED, payload: user })
console.log(user)
} catch (e) {
console.error(e)
}
};
};
这是我的index.js
store.dispatch(checkLoggedIn())
if(localStorage.donedeal){
setAuthHeader(localStorage.donedeal);
store.dispatch(getUserProfile())
}
ReactDOM.render(
<Provider store ={store}>
<App />
</Provider>
, document.getElementById('root'));
Navbar.js
import React from "react";
import "./navbar.css";
import { connect } from "react-redux";
import { logOut} from "../../actions/login";
// import { Link } from "react-router-dom";
import logo from './logo.png'
const Navbar = ({ isAuth, logOut, profile}) => {
return (
<header>
<img src={logo} alt="Logo" className="logo" />
<nav className="nav_links">
<li><p> Buy and sell <span className="bold"> your things </span> </p></li>
<a className="cta" href=""><button> <li className="fas fa-plus"></li> Place ad </button></a>
{/* <li><a href=""> Sign up</a></li> */}
{/* <li><a href=""> Login</a></li> */}
{isAuth ? (
<div>
<p>{profile.firstName}</p>
<button onClick={() => logOut()}> Logout </button>
</div>
) : (<div><button> Login </button><button>Register</button></div>)
}
</nav>
</header>
);
};
const mapStateToProps = ({ login }) => {
return {
isAuth: login.isAuthenticated,
profile: login.profile
};
};
export default connect(
mapStateToProps,
{ logOut}
)(Navbar);
上面的代码无处不在,因为我只是在试验它,但是它正在注册并登录用户,甚至获取个人资料,但我无法显示信息。
[可能有某种类型或我做错的事情看不到
非常感谢您的帮助。
AuthAction调用apiLogin(axios)然后它返回数据然后设置标题然后我们调用profileAction并调度成功和错误(尚未实现)
export const signIn = request_data => {
console.log('Authenticating action is called ....................')
return async dispatch => {
try {
const {
data: { token }
} = await apiLogin(request_data);
setAuthHeader(token);
dispatch(getUserProfile());
dispatch(success(token));
} catch (e) {
const {
response: { data }
} = e;
dispatch(error(data.error));
}
};
};
getUserProfile
export const getUserProfile = () => { return async dispatch => { console.log('Fetching User profile....................') try { const { data: { user } } = await apiFetchProfile(); dispatch({ type: PROFILE_FETCHED, payload: user }); console.log(user) } catch (e) { console.error(e); } }; }; const success = token => { localStorage.setItem(TOKEN_NAME, token); return { type: AUTH_SUCCESS }; }; const error = error => { return { type: AUTH_FAILED, payload: error }; };
authReducer.js
const INITIAL_STATE = { isAuth: false, profile: {}, error: null }; export default (state = INITIAL_STATE, action) => { switch (action.type) { case AUTH_SUCCESS: return { ...state, isAuth: true, error: null }; case AUTH_FAILED: return { ...state, isAuth: false, error: action.payload }; case USER_LOGGED_OUT: return { ...state, isAuth: false, profile: {} }; case PROFILE_FETCHED: return { ...state, profile: action.payload }; default: return state; } }; export const checkToken = () => { console.log('Checking LStorage is called ....................') return dispatch => { try { const token = localStorage.getItem(TOKEN_NAME); if (token === null || token === "undefined") { return dispatch(error("You need to login ")); } setAuthHeader(token); dispatch(getUserProfile()); dispatch(success(token)); } catch (e) { console.error(e); } }; };
index.js
import {checkToken} from './actions/auth_actions' import store from './store' // import setAuthHeader from './api/setAuthHeader' // import jwt from 'jsonwebtoken'; store.dispatch(checkToken()); ReactDOM.render( <Provider store ={store}> <App /> </Provider> , document.getElementById('root'));
这些是我所做的更改,现在可以正常使用现在我必须处理错误所以基本上,SignIn操作调用后端API,它返回令牌,然后我们发送authHeader,同时我调用getUserProfile,它调用后端并获取用户配置文件然后,我创建了一个动作,该动作将在应用程序的开始处在index.js中调用,因此,如果用户重新加载页面,我们将再次分派用户配置文件,这就是问题所在
希望这对某人有帮助
以上是关于[在Redux中获取用户个人资料时发生TypeError的主要内容,如果未能解决你的问题,请参考以下文章