React JS和Redux:this.props未定义

时间:2018-08-20 14:26:09

标签: javascript reactjs redux typeerror

我已经阅读了很多有关我的问题的主题,但没有一个主题对我有帮助。

我使用React.JS和Redux开发了一个JWT身份验证应用程序,并以django rest框架API作为后端。

用户信息通过GET请求发送给经过身份验证的用户:

{
    "id": 1,
    "email": "",
    "first_name": "",
    "last_name": ""
}

user.actions.js(redux操作)

export const loadUser = () => {
  return (dispatch) => {
    const token = localStorage.getItem('token');
    if (token) {
      axios.get('http://localhost:8000/auth/user/', {
        headers: { 'Authorization': 'token ' + token }
      })
        .then(res => {
          dispatch({ type: USER_LOADED, data: JSON.stringify(res.data) })
        }).catch((error) => {
          // catch later
        })
    }
  };
};

auth.reducers.js

import {
  SIGNIN_REQUEST,
  SIGNIN_SUCCESS,
  SIGNIN_FAILURE,
  SIGNOUT,
  USER_LOADED
} from '../_constants/user.constants';

const initialState = { }

export function auth(state = {}, action) {
  switch (action.type) {
    case SIGNIN_REQUEST:
      return { ...state, isLogging: true }
    case SIGNIN_SUCCESS:
      return { ...state, isLogged: true }
    case SIGNIN_FAILURE:
      return { ...state, error: action.data, isLogged: false, isLogging: false }
    case USER_LOADED:
      return { ...state, isLogged: true, user: action.data }
    case SIGNOUT:
      return { }
    default:
      return state;
  }
};

App.js

class App extends Component {

  componentDidMount() {
    let token = localStorage.getItem('token');
    if (token) {
      this.props.loadUser();
    }
  }

  render() {
    return (
      <div className="container-scroller">
        <BrowserRouter>
          <Router history={History}>
            <Switch>
              ...
            </Switch>
          </Router>
        </BrowserRouter>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    auth: state.auth
  }
}

const mapDispatchToProps = dispatch => {
  return {
    loadUser: () => {
      return dispatch(userActions.loadUser());
    }
  }
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

一切正常。数据已正确提取。当我在render方法中编写{this.props.auth.user}时,它会正确显示数据(由API发送):

{“ id”:1,“电子邮件”:“”,“名字”:null,“姓氏”:null}

但是当我尝试显示数据值(id,email等)时,它会显示错误:(使用map或this.props.auth.user ['id']

TypeError:this.props.auth.user未定义

如何正确显示数据?

预先感谢:)

0 个答案:

没有答案