简体   繁体   中英

React.js setState does not re-render child component

I am passing a list from the parent component's state to a child component's <CheckboxList /> props . The list should then show in the child component. After fetching the list elements from the database I use setState to update the list but the child component is not re-rendered with the new list.

class ParentComponent extends Component {

    state = {
        users: [{ username: 'before' }]
    }

    componentDidMount() {
        const result = [];
        db.collection("users").get().then((querySnapshot) => {
            querySnapshot.forEach(function (doc) {
                let user = doc.data();
                result.push(user);
            });
        }).then(() => {
            this.setState({
                users: result
            })
        })
    }

    render() {

        return (
            <div>
                <h1>List of users</h1>
                <CheckboxList list={this.state.users} />
            </div>
        )
    }
}

The list shows before and it does not update with content from the database. I checked and the values are fetched from the database, they are just not passed to the <CheckboxList /> after the setState . Can anybody help me?

The problem was that I was retrieving the list from the CheckboxList status and then using it through that. Now I have fixed it. I am retrieving it in the CheckboxList render() , storing it into a variable and then using it from there.

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