简体   繁体   中英

ReactJS | Map through nested objects

I have the following object coming from the BE. I load it through redux, onto a property inside my Component called user . This is the schema:

{
    user: 'root',
    perm: [
      "admin",
      "write",
      "read",
      "nodata"
    ],
    "auth": {
      "mode1": true,
      "mode2": true,
      "mode3": false
    }
}

What I want to do, is actually, map through the auth field, and for every mode, print in a span the name of each mode(THE KEY OF THE OBJECT).

So, I created a little renderSpan method to create the necessary boilerplate to map through:

  renderSpan = (authKey: string): JSX.Element => {
    const { user } = this.props;
    return (
      <div key={authKey}>
        {user && user.auth && <span> {user.auth[securityKey]}</span>}
      </div>
    );
  };

Then I mapped through it on my main render block:

  renderAuthModes = () => {
    const { user } = this.props;
    return (
      <Fragment>
        {user && user.auth && (
          <div className="container-fluid">
            {JSON.stringify(user.auth, null, 2)} // This prints the 3 modes
              <div>
                {Object.keys(user.auth).map(authKey => this.renderSpan(authKey))}
              </div>
          </div>
        )}
      </Fragment>
    );
  };

What I get in return, is 3 div with empty spans. The divs are rendered on to the DOM, but nothing is printed on the display. What am I doing wrong?

The Application is in React-Redux and Typescript.

 {user.auth.[securityKey]}</span>}

Should be

 {user.auth[securityKey]}</span>}

Besides that everything works fine. The problem is that you are just rendering a span tag with a boolean inside, so the content will be empty... Try something like this:

<span> {user.auth[securityKey] ? 'true' :'false'}</span>

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