React: Trying to render props that populate AFTER

2019-07-26 02:09发布

In my React app, I want to render a prop value, but it does not exist until the props have been updated which occurs after the render is complete.

this.props.users is an object, so I use Object.keys() to translate into an array, and then map through the child elements using the keys to target them:

// ...
render() {
   return {
     <div className='users-list'>
        <h4>Users List</h4>
        {!isLoaded(users) ? '' :
           Object.keys(users).map( (key, i) => <p>{users[key].email}</p> )
        }
     </div>
   }
}

This works, but it took me a lot of hacking and adapting the code to get there. Is there a better/more eloquent way to go about this? Because I imagine this is really common case! Does the component lifecycle come into it?

Any help/suggestions appreciated.

1条回答
戒情不戒烟
2楼-- · 2019-07-26 02:36

Give it a default?

const users = this.props.users || {};

Using ES6 and destructuring:

const { users = {} } = this.props;
查看更多
登录 后发表回答