【发布时间】:2020-10-15 13:06:12
【问题描述】:
我正在尝试创建个人资料页面以显示单个用户的特定数据。 当我想使用 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
}
【问题讨论】:
-
initialState = null,这是在组件中还是在商店中?
-
在商店..
-
你检查过axios是否正常工作吗?
-
我认为问题来自 axios 我认为它没有将请求发送到我在 chrome 上检查网络工具的 api ,我不知道我做错了什么!!!
标签: javascript reactjs express redux axios