简体   繁体   中英

ReactJS not rerendering after setState

I have a simple ReactJS application that loads a list of users and shows a record for each user.

This is the component handling the loading of the users and showing them in a list, while the UserCard component will visualize the user information and allow for edits.

export default class UserManager extends React.Component {
constructor() {
    super();

    this.state = {
        users:[]
    };
};

componentDidMount() {
    this.loadUsers();
};

loadUsers() {
    $.getJSON('/api/users').then((data) => {
        this.setState({ users: data.items });
    });
};

render() {
    return (
        <div className="animated fadeIn">
            <div className="row">
                <div className="col-sm-8 col-md-10">
                    <div id="userslist" className="userlist" >
                        {
                            this.state.users.map((user) => {
                                <UserCard user={user} />
                            })
                        }
                    </div>
                </div>
            </div>
        </div>
    )
}

}

I load the users on componentDidMount, and the api call returns successfully with all user data. The rendering of the users is however not triggered. The list will remain empty.

Am I missing something here? Do I have to trigger the rendering manually again?

Return the UserCard component from map body, if you don't return anything then, it will return undefined by default:

<div id="userslist" className="userlist" >
    {
        this.state.users.map((user) => {
            return  <UserCard user={user} />
        })
    }
</div>

Or write it like this without using {} because, you just want to return a component without any calculation or condition so {} is not required:

<div id="userslist" className="userlist" >
    {
        this.state.users.map((user,i) => <UserCard key={i} user={user} /> )
    }
</div>

Assign the unique key to each UserCard .

To add to @Mayank answer, you probably can do it without writing an explicit return statement, by using () instead of {} after the map function since it automatially returns the JSX inside it by default

        <div id="userslist" className="userlist" >
                    {
                        this.state.users.map((user) => (
                            <UserCard user={user} />
                        ))
                    }
                </div>

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