简体   繁体   中英

Error: Objects are not valid as a React child (found: object with keys {zip})

I get this error when using this code:

 const App = () => {

  const user = {name: "ff", address: {zip: "Henry street"}};

  const zip = user ? user.address: undefined ? user.address.zip : undefined;
  return (
    <div className="App">
      <div>bnm {zip}</div>  
    </div>
  );

} 

When I output the zip variable it shows this: {zip: "Henry street"} This error goes away and it prints out the proper thing when I do this:

 const zip = (user ? user.address: undefined) ? user.address.zip : undefined;

Does anybody know why it doesn't work without the parentheses?

Does anybody know why it doesn't work without the parentheses?

Because of operator associativity . The conditional operator has right-to-left associativity. You can think of this as if the operator is trying to find the longest valid expression after the colon and uses that as the alternative value. Thus your expression is evaluated as

user ? user.address : (undefined ? user.address.zip : undefined)

Ie if user is "truthy", user.address is returned, which is the object mentioned in the error.

The precedence/associativity is not always obvious or well known, therefore its useful to add parenthesis to make the order of evaluation clearer even if doesn't change it.

There are clearer and less error prone ways to express the same logic:

You can use the optional chaining operator:

const zip = user?.address?.zip;

Or you can use a plain old if statement:

let zip;
if (user && user.address) {
  zip = user.address.zip;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM