How to update object in React state

后端 未结 5 1356
野的像风
野的像风 2021-02-18 22:30

I have an indexed list of users in the JS object (not array). It\'s part of the React state.

{
    1: { id: 1, name: \"John\" }
    2: { id: 2, name         


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-02-18 23:23

    If you're not using Flux, you use this.setState() to update the state object.

    delUser(id) {
        const users = this.state.users;
        delete users[id];
        this.setState(users);
    }
    
    addChangeUser(id, name) {
        const users = this.state.users;
        users[id] = {id: id, name: name};
        this.setState(users);
    }
    

    Then you can execute your test cases with this:

    addChangeUser(4, 'Jane);
    addChangeUser(2, 'Peter');
    delUser(2);
    

提交回复
热议问题