
[英]TypeError: Cannot read property 'firstname' of null (react js redux firebase)
[英]React Redux : TypeError: Cannot read property 'user' of null
我正在尝试创建个人资料页面以显示单个用户的特定数据。 当我想使用 connect 获取配置文件状态时的问题返回 null ! 配置文件状态应该有来自后端的负载
在 Profile.js 中
const Profile = ({ getProfileById, profile: { profile }, auth, match }) => {
console.log(profile);
useEffect(() => {
getProfileById(match.params.id);
}, [getProfileById, match.params.id]);
console.log(profile);
return (
<Fragment>
{profile === null ? (<Spinner/>) : (<Fragment>
<Link to="/Profiles" className="btn btn-light">
Back To Profiles
</Link>
</Fragment>)}
{auth.isAuthenticated &&
auth.loading === false &&
auth.user._id === profile.user._id && (
<Link to="/edit-profile" className="btn btn-dark">
Edit Profile
</Link>
)}
<div className="profile-grid my-1">
// when I pass profile as prop returns null
<ProfileTop profile={profile} />
</div>
</Fragment>
)
}
Profile.propTypes = {
getProfileById : PropTypes.func.isRequired,
profile : PropTypes.object.isRequired,
auth : PropTypes.object.isRequired,
}
const mapStateToProps = (state) => ({
profile: state.profile,
auth: state.auth
});
export default connect(mapStateToProps,{getProfileById}) (Profile)
在 ProfileTop.js 中
const ProfileTop = ({profile : {
// Here showes the error ×
//TypeError: Cannot read property 'company' of null
company,
location,
social,
user : {name,avatar}
}}) => {
return (
<div className="profile-top bg-primary p-2">
<img
src={avatar}
alt=""
className="round-img"
/>
</div>
)
}
ProfileTop.propTypes = {
profile : PropTypes.object.isRequired,
}
export default ProfileTop
注意:在我添加功能之前,当我看到 redux 开发工具时,配置文件不等于 null
这是 getProfileById 操作..
export const getProfileById = userId => async dispatch => {
try {
const res = await axios.get(`/profile/user/${userId}`);
dispatch({
type: GET_PROFILE,
payload: res.data
});
} catch (err) {
console.log(err);
dispatch({
type: PROFILE_ERROR,
payload: { msg: err.response.statusText, status: err.response.status }
});
}
};
初始状态..
const initialState = {
profile : null,
profiles : [],
repos : [],
loading : true ,
error : {}
}
GET_PROFILE 减速器
case GET_PROFILE :
return {...state,
profile : payload,
loading : false
}
哎呀,伙计们,我解决了这个问题,因为我没有注意到 Fragment 的结束标签 😅 今天的课程当你熬夜超过 20 小时时不会编码..
return (
<Fragment>
{profile === null ? (<Spinner/>) : (<Fragment>
<Link to="/Profiles" className="btn btn-light">
Back To Profiles
</Link>
// here I close the fragment normally profile will returns null
// I should close it right after the closing div
</Fragment>)}
{auth.isAuthenticated &&
auth.loading === false &&
auth.user._id === profile.user._id && (
<Link to="/edit-profile" className="btn btn-dark">
Edit Profile
</Link>
)}
<div className="profile-grid my-1">
<ProfileTop profile={profile} />
</div>
</Fragment>
)
}
Profile 必须从 action.payload 而不是从负载中获取数据。
return {
...state,
profile : action.payload,
loading : false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.