React useContext-访问嵌套对象(未定义)

时间:2020-03-07 09:36:53

标签: javascript reactjs react-hooks

我是一个后端人员,正在尝试我的第一个react / JS应用。

我正试图从AuthContext传递一些auth数据,以便在另一个组件中进行提取,但我终生无法找出原因。

user是一个嵌套对象,如下所示: user

我可以访问诸如user.username之类的第一级对象,但是更深入地访问诸如user.signInUserSession.accessToken之类的对象,每次都会变得不确定。

我什至可以使用$r.hooks[0].value.signInUserSession.accessToken.jwtToken在react dev工具中访问jwtToken。

AuthContext.js

import React, {createContext, useEffect, useState} from 'react';
import {Auth} from "aws-amplify";

export const AuthContext = createContext(false);

const AuthContextProvider = (props) => {
    const [user, setUser] = useState([false]);

    useEffect(() => {
        Auth.currentAuthenticatedUser()
            .then(user => setUser(user))
            .catch(err => console.log(err));
    }, []);

    return (
        <AuthContext.Provider value={user}>
            {props.children}
        </AuthContext.Provider>
    );

};
export default AuthContextProvider;

Body.js

import React, { useState, useEffect, useContext } from 'react';
import {Content} from "./styles"
import {AuthContext} from "../../../contexts/AuthContext";


function Body() {
    const user = useContext(AuthContext);

    const [investor, setInvestor] = useState([]);

    const jwtToken = user.signInUserSession.accessToken.jwtToken;

    useEffect(() => console.log("Bearer ".concat(jwtToken)), [user]);

    useEffect(() => {
        fetch("https://DOMAIN/investors/overview/v3/?token=".concat(jwtToken), {
            method: 'GET',
            headers: {
                'Authorization': "Bearer ".concat(jwtToken)
            }
        })
            .then(response => response.json())
            .then((responseData) => {
                setInvestor(responseData);
            })
            .catch(error => setInvestor({ error }));
    }, [user]);

    return (
        <Content>{investor.total_value}</Content>
    )
}

export default Body

对于我所缺少的任何帮助,我们深表感谢!

编辑-从devTools复制的实际对象(不知道如何直接检查实际用户对象吗?):

[
  {
    "name": "Context",
    "value": {
      "username": "XXX",
      "pool": "{advancedSecurityDataCollectionFlag: true, client: …}",
      "Session": null,
      "client": "{endpoint: \"https://cognito-idp.ap-southeast-2.amaz…}",
      "signInUserSession": {
        "idToken": {
          "jwtToken": "MDRjYmUiLCJhdWQiOiI0dmRwbmo2b2JhaGpyc25hbmtkNvdXRoZUiOiJwb3dlcndy...",
          "payload": "{aud: \"4vdpnj6obahjrsnankda91s2va\", auth_time: 1583…}",
          "constructor": "ƒ CognitoIdToken() {}",
          "getJwtToken": "ƒ getJwtToken() {}",
          "getExpiration": "ƒ getExpiration() {}",
          "getIssuedAt": "ƒ getIssuedAt() {}",
          "decodePayload": "ƒ decodePayload() {}"
        },
        "refreshToken": {
          "token": "iJKXkXkGbJbBgnRPMN84TWBdsES-mZBGN3yxGd-6555-a67nsFuB9UZKG-s-mk3EHRqs-WfeDxpOw9ia5OtI-ZZTNh2pK...",
          "getToken": "ƒ getToken() {}"
        },
        "accessToken": {
          "jwtToken": "GET_THIS_TOKEN.zb3V0aGVhc3QtMi5hbWpIjoi...",
          "payload": "{auth_time: 1583469821, client_id: n…}",
          "constructor": "ƒ CognitoAccessToken() {}",
          "getJwtToken": "ƒ getJwtToken() {}",
          "getExpiration": "ƒ getExpiration() {}",
 .........

0 个答案:

没有答案