React: Trying to render props that populate AFTER render

北城余情 提交于 2019-12-11 06:27:24

问题


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:


Give it a default?

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

Using ES6 and destructuring:

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


来源:https://stackoverflow.com/questions/41706381/react-trying-to-render-props-that-populate-after-render

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!