React访问带冒号的AWS Cognito自定义属性报错,求解决
Hey there! The parsing error you're hitting is totally common when dealing with object keys that have special characters like colons. Let's break down what's going on and fix it.
The Root Issue
JavaScript's dot notation (like user.attributes.family_name) only works for keys that are valid identifiers—meaning they can't have colons, spaces, or other non-standard characters. Since your custom attribute is named custom:company_name, dot notation throws a syntax error because the colon isn't allowed in that context.
The Fix: Bracket Notation
Instead of dot notation, use bracket notation to access keys with special characters. Here's how to update your code:
1. Fix the Variable Assignment
Replace this problematic line:
const company_name = user.attributes.custom:company_name; // ERROR occurs here
With:
const company_name = user.attributes['custom:company_name'];
2. Direct Access in JSX (if you use it)
If you ever need to reference the attribute directly in your JSX (like your initial attempt), use brackets there too:
<a class="uk-text">{user.attributes['custom:company_name']}</a>
Why This Works
- Dot notation: Best for simple keys (letters, numbers, underscores) like
given_nameorfamily_name—these are valid JavaScript identifiers. - Bracket notation: Works for any key, regardless of special characters. You just wrap the key string in quotes inside the brackets.
Full Corrected Code Snippet
Here's the updated render method of your ProfilePage component:
render() { const { user } = this.props; console.log(user.attributes); const emailVerified = this.props.user.attributes.email_verified; const company_name = user.attributes['custom:company_name']; // Fixed line return ( <> <div class="container"> {/* ... rest of your existing JSX ... */} <div class="uk-margin"> <label class="uk-form-label" for="form-stacked-text">Name</label> <div class="uk-form-controls"> <a class="uk-text">{company_name}</a> {/* Now works correctly */} </div> </div> {/* ... rest of your existing JSX ... */} </div> </> ); }
That should resolve the parsing error and let you access your custom Cognito attribute without issues. Happy coding!
内容的提问来源于stack exchange,提问作者Matthew

