开发者问题收集

React Redux:TypeError:无法读取 null 的属性“用户”

2020-10-15
335

我正在尝试创建个人资料页面以显示单个用户的特定数据。 当我想使用 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 dev tools 时,个人资料不等于 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 Reducer

case GET_PROFILE : 
return {...state,
    profile : payload,
    loading : false
}
2个回答

哎呀伙计们,我解决了这个问题,是因为我没有注意到 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>
    )
}
Fabio
2020-10-15

配置文件必须从 action.payload 获取数据,而不是从 payload 获取。

return {
    ...state,
    profile : action.payload,
    loading : false
}
Dan
2020-10-15