MERN Stack-TypeError:无法将未定义或null转换为对象

时间:2019-04-05 20:07:06

标签: javascript node.js reactjs express mern

我跟着Traversy Media的MERN Stack,从前到后的课程。我正在尝试设置应用程序的登录部分。我确保我的代码与他的完全相同。但是我得到了错误TypeError: Cannot convert undefined or null to object,而他却没有。

我一直在github上阅读,人们说这是reactstrap的问题,与依赖有关吗?这是我的头。我尝试运行npm ci,尝试更改json-package-lock文件,尝试制作npm-shrinkwrap文件,依此类推,如此处https://github.com/reactstrap/reactstrap/issues/1373和此处https://github.com/reactstrap/reactstrap/issues/1374所述,但到目前为止没有任何效果,会产生完全相同的错误。

authActions.js:

import axios from "axios";
import setAuthToken from "../utils/setAuthToken";
import jwt_decode from "jwt-decode";

import { GET_ERRORS, SET_CURRENT_USER } from "./types";

// Register User
export const registerUser = (userData, history) => dispatch => {
  axios
    .post("/api/users/register", userData)
    .then(res => history.push("/login"))
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

// Login - Get User Token
export const loginUser = userData => dispatch => {
  axios
    .post("/api/users/login", userData)
    .then(res => {
      // Save to localStorage
      const { token } = res.data;
      // Set token to ls
      localStorage.setItem("jwtToken", token);
      // Set token to Auth header
      setAuthToken(token);
      // Decode token to get user data
      const decoded = jwt_decode(token);
      // Set current user
      dispatch(setCurrentUser(decoded));
    })
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

// Set logged in user
export const setCurrentUser = decoded => {
  return {
    type: SET_CURRENT_USER,
    payload: decoded
  };
};

Dashboard.js:

import React, { Component } from "react";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { getCurrentProfile } from "../../actions/profileActions";
import Spinner from "../common/Spinner";

class Dashboard extends Component {
  componentDidMount() {
    this.props.getCurrentProfile();
  }

  render() {
    const { user } = this.props.auth;
    const { profile, loading } = this.props.profile;

    let dashboardContent;

    if (profile === null || loading) {
      dashboardContent = <Spinner />;
    } else {
      // Check if logged in user has profile data
      if (Object.keys(profile).length > 0) {
        dashboardContent = <h4>TODO: DISPLAY PROFILE</h4>;
      } else {
        // User is logged in but has no profile
        dashboardContent = (
          <div>
            <p className="lead text-muted">Welcome {user.name}</p>
            <p>You have not yet setup a profile, please add some info</p>
            <Link to="/create-profile" className="btn btn-lg btn-info">
              Create Profile
            </Link>
          </div>
        );
      }
    }

    return (
      <div className="dashboard">
        <div className="container">
          <div className="row">
            <div className="col-md-12">
              <h1 className="display-4">Dashboard</h1>
              {dashboardContent}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

Dashboard.propTypes = {
  getCurrentProfile: PropTypes.func.isRequired,
  auth: PropTypes.object.isRequired,
  profile: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  profile: state.profile,
  auth: state.auth
});

export default connect(
  mapStateToProps,
  { getCurrentProfile }
)(Dashboard);

预期:加载一个我可以登录的页面,然后在登录时显示“欢迎使用user.name。您尚未设置个人资料,请添加一些信息”

实际结果:

TypeError: Cannot convert undefined or null to object
Dashboard.render
src/components/dashboard/Dashboard.js:23

  20 |   dashboardContent = <Spinner />;
  21 | } else {
  22 |   // Check if logged in user has profile data
> 23 |   if (Object.keys(profile).length > 0) {
     | ^  24 |     dashboardContent = <h4>TODO: DISPLAY PROFILE</h4>;
  25 |   } else {
  26 |     // User is logged in but has no profile

另外,将其搁置一会儿后,如果回到它上面,它将加载我可以登录的页面,但是当我使用我在数据库中注册的用户的登录信息时,它会给出我这个错误:

(anonymous function)
src/actions/authActions.js:39
  36 |     .catch(err =>
  37 |       dispatch({
  38 |         type: GET_ERRORS,
> 39 |         payload: err.response.data
  40 |       })
  41 |     );
  42 | };

当我重新加载时,它又返回给我上面显示的另一个错误(TypeError: Cannot convert undefined or null to object错误)

1 个答案:

答案 0 :(得分:0)

您的代码有几个问题。最明显的是您如何检查profile

if (profile === null || loading)

我认为正在发生的事情是profile被设置为undefined,而loading被设置为false,因此,它正在通过{{1} }语句。

相反,最初将if设置为空对象profile。然后,您可以使用lodash的{}函数检查它是否仍然为空。这也将使您的isEmpty()验证为1:1。如果它是一个对象,则它是一个对象。如果是字符串,则保留字符串,依此类推。再次保持1:1。

此外,在检查道具的类型时,请描述propTypes中的shape。有时候,您通常会喜欢使用object,并且会因使用诸如eslintProptypes.array之类的通用描述符而引发错误。尽管这看起来有些过分,但是如果属性与所描述的形状有所区别,则它可以突出显示对象内的错误。

工作代码和框

Edit Restructured App


此示例包含一些高级/中间代码用法,因此我想其中的某些用法是没有意义的。如果您有任何疑问,请随时提问。

在此代码示例中使用:ES6 object desctucturingfat arrow functions with simplified returnsfat arrow class propertiesthe spread operatorternary operator

代码的重构和简化版本...

容器/仪表板

Proptypes.object

reducers / profileReducer

import isEmpty from "lodash/isEmpty";
import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { getCurrentProfile } from "../../actions/profileActions";
import DisplayUser from "../../components/DisplayUser";
import DisplaySignUp from "../../components/DisplaySignUp";
import Spinner from "../../components/Spinner";

// using a PureComponent because we're not utilizing state, 
// but we're utilizing the "componentDidMount" lifecycle
class Dashboard extends PureComponent { 
  componentDidMount = () => {
    this.props.getCurrentProfile(1);
  }

  // the below can be read like so:
  // if "isLoading" is true...  then show a spinner
  // else if "currentUser" is not empty... then display the user details
  // else show a signup message
  render = () => (
    this.props.isLoading ? (    
      <Spinner />  
    ) : !isEmpty(this.props.currentUser) ? ( 
      <DisplayUser currentUser={this.props.currentUser} /> /
    ) : (
      <DisplaySignUp />  
    )
}

// describing the shape of the "currentUser" object 
// notice that there aren't any required declarations 
// within the object itself because "currentUser" is initially 
// an empty object; however, when it's not empty, it should 
// follow this structure
Dashboard.propTypes = {
  getCurrentProfile: PropTypes.func.isRequired,
  currentUser: PropTypes.shape({ 
    id: PropTypes.number,
    name: PropTypes.string,
    username: PropTypes.string,
    email: PropTypes.string,
    address: PropTypes.shape({
      street: PropTypes.string,
      suite: PropTypes.string,
      city: PropTypes.string,
      zipcode: PropTypes.string,
      geo: PropTypes.objectOf(PropTypes.string)
    }),
    phone: PropTypes.string,
    website: PropTypes.string,
    company: PropTypes.objectOf(PropTypes.string)
  }).isRequired,
  isLoading: PropTypes.bool.isRequired
};

export default connect(
  state => ({
    currentUser: state.profile.currentUser,
    isLoading: state.profile.isLoading
  }),
  { getCurrentProfile }
)(Dashboard);