【问题标题】:React Redux : TypeError: Cannot read property 'user' of nullReact Redux:TypeError:无法读取 null 的属性“用户”
【发布时间】: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


【解决方案1】:

Ooopes 伙计们,我解决了这个问题,因为我没有注意到 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>
    )
}

【讨论】:

    【解决方案2】:

    Profile 必须从 action.payload 中获取数据,而不是从 payload 中获取数据。

    return {
        ...state,
        profile : action.payload,
        loading : false
    }
    

    【讨论】:

    • 我在上面用 const { type,payload} = action; 解构了
    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2020-05-13
    • 2021-10-31
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多