【问题标题】:Not able to access an id property from props in React无法从 React 中的道具访问 id 属性
【发布时间】:2019-03-13 11:58:52
【问题描述】:

我正在尝试构建一个 React 应用程序,用户可以在其中将特定内容保存在他们的 ID 下。 我正在使用带有 React 和 auth0 的 nodeJS 进行身份验证。

我正在尝试访问 this.props.auth 对象上的属性并查找该属性是否存在于我的数据库中,因此如果存在匹配项,则可以将某些内容保存在用户 ID 下。

但是我无法访问 this.props.auth.id,如下面的代码所示,但我可以访问 this.props.auth

有什么建议吗? . . .

Auth.js

import history from '../../history';
import auth0 from 'auth0-js';
import { AUTH0_CONFIG } from '../../auth0';
import API from "../../utils/API"




export default class Auth {
  accessToken;
  idToken;
  expiresAt;
  userProfile;
  userImage;
  name;
  id;



  auth0 = new auth0.WebAuth({
    domain: AUTH0_CONFIG.domain,
    clientID: AUTH0_CONFIG.clientId,
    redirectUri: AUTH0_CONFIG.callbackUrl,
    responseType: 'token id_token',
    scope: 'openid profile'
  })



  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.getAccessToken = this.getAccessToken.bind(this);
    this.getIdToken = this.getIdToken.bind(this);
    this.renewSession = this.renewSession.bind(this);
    this.userInfo = this.userInfo.bind(this)
  }

  login() {
    this.auth0.authorize();
  }

  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
        API.saveUser(authResult.idTokenPayload);
        history.replace('/')
      } else if (err) {
        history.replace('/');
        console.log(err);
        alert(`Error: ${err.error}. Check the console for further details.`);
      }
    });
  }

  getAccessToken() {
    return this.accessToken;
  }

  getIdToken() {
    return this.idToken;
  }

  userInfo() {
    return this.userProfile
  }

  setSession(authResult) {
    // Set isLoggedIn flag in localStorage
    localStorage.setItem('isLoggedIn', 'true');
    console.log(authResult);
    let expiresAt = (authResult.expiresIn * 1000) + new Date().getTime();
    this.accessToken = authResult.accessToken
    this.idToken = authResult.idToken;
    this.expiresAt = expiresAt;
    this.userImage = authResult.idTokenPayload.picture;
    this.name = authResult.idTokenPayload.name.split(' ', 1);
    this.id = authResult.idTokenPayload.nickname;


    // navigate to the home route
    history.replace('/');

  }

  renewSession() {
    this.auth0.checkSession({}, (err, authResult) => {
       if (authResult && authResult.accessToken && authResult.idToken) {
         this.setSession(authResult)
         console.log('authresult', authResult);

       } else if (err) {
         this.logout();
         console.log(err);
         alert(`Could not get a new token (${err.error}: ${err.error_description}).`);
       }
    });
  }

  logout() {
    // Remove tokens and expiry time
    this.accessToken = null;
    this.idToken = null;
    this.expiresAt = 0;

    // Remove isLoggedIn flag from localStorage
    localStorage.removeItem('isLoggedIn');

    // navigate to the home route
    history.replace('/');
  }

  isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiry time
    let expiresAt = this.expiresAt;
    return new Date().getTime() < expiresAt;
  }


}

Home.js

class Home extends Component {

  constructor(props) {
    super(props)
    console.log(this.props); // can access this
    console.log(this.props.auth.id); // this shows undefined
    this.state = {
      news: [],
      summary:[],
      summaryUrl: '',
      userID: '',
      user: '', // 
      pageLoading: true,
      gistLoading: true
    }
    // console.log(this.state);
  }

  goTo(route) {
  // console.log(history, route);
  this.props.history.replace(`/${route}`)
  }

  login() {
    this.props.auth.login();
  }

  logout() {
    this.props.auth.logout();
  }

  // API call to display trending news

  componentDidMount() {

    API.getArticles()
      .then(res => {
        this.setState({
          news: res.data,
          pageLoading: false,
          // user: this.props.auth.id
        })
        // console.log(this.state);
      });

      API.getSavedUsers()
        .then((res) => {
          console.log();

          res.data.forEach((el) => {
            console.log(this.props.auth.id); // shows undefined
            if(el.name ===  this.props.auth.id){
              this.setState({
                userID: el.authID
              })
            } else {
              console.log('notfound');
            }
          })
          console.log(this.state);
        })


    const { renewSession } = this.props.auth;
    if (localStorage.getItem('isLoggedIn') === 'true') {
      renewSession();
    }
  }

【问题讨论】:

    标签: node.js reactjs auth0 react-props


    【解决方案1】:

    我可能是错的,但从快照中,auth 属性的数据类型是Auth,这是一个对象,但如果你看它,匹配、位置等都显示为{…},这象征着它的一个对象和因此我们使用点来获取属性。我建议先解析 auth,然后访问内部属性,如下所示:

    const auth = JSON.parse(this.props.auth);
    console.log(auth.id);
    

    你能试试这个吗?

    【讨论】:

      猜你喜欢
      • 2019-11-05
      • 1970-01-01
      • 2019-02-27
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 2011-01-14
      相关资源
      最近更新 更多