How can I remove an attribute from a Reactjs component's state object

后端 未结 10 1988
南笙
南笙 2020-12-06 09:17

If I have a react component that had a property set on it\'s state:

onClick() {
    this.setState({ foo: \'bar\' });
}

Is it possible to re

相关标签:
10条回答
  • 2020-12-06 09:46

    If the removal is in a function and the key needs to be a variable, try this :

    removekey = (keyname) => {
        let newState = this.state;
        delete newState[keyname];
        this.setState(newState)
        // do not wrap the newState in additional curly braces  
    }
    
    this.removekey('thekey');
    

    Almost the same as steve's answer, but in a function.

    0 讨论(0)
  • 2020-12-06 09:47

    Use dot-prop-immutable

    import dotPropImmutable from "dot-prop-immutable";
    
    onClick() {
        this.setState(
           dotPropImmutable.delete(this.state, 'foo')
        );
    }
    
    0 讨论(0)
  • 2020-12-06 09:50

    You can use Object.assign to make a shallow copy of your application's state at the correct depth and delete the element from your copy. Then use setState to merge your modified copy back into the application's state.

    This isn't a perfect solution. Copying an entire object like this could lead to performance / memory problems. Object.assign's shallow copy helps to alleviate the memory / performance concerns, but you also need to be aware of which parts of your new object are copies and which parts are references to data in the application state.

    In the example below, modifying the ingredients array would actually modify the application state directly.

    Setting the value of the undesired element to null or undefined doesn't remove it.

    const Component = React.Component;
    
    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          "recipes": {
            "1": {
              "id": 1,
              "name": "Pumpkin Pie",
              "ingredients": [
                "Pumpkin Puree",
                "Sweetened Condensed Milk",
                "Eggs",
                "Pumpkin Pie Spice",
                "Pie Crust"
              ]
            },
            "2": {
              "id": 2,
              "name": "Spaghetti",
              "ingredients": [
                "Noodles",
                "Tomato Sauce",
                "(Optional) Meatballs"
              ]
            },
            "3": {
              "id": 3,
              "name": "Onion Pie",
              "ingredients": [
                "Onion",
                "Pie Crust",
                "Chicken Soup Stock"
              ]
            },
            "4": {
              "id": 4,
              "name": "Chicken Noodle Soup",
              "ingredients": [
                "Chicken",
                "Noodles",
                "Chicken Stock"
              ]
            }
          },
          "activeRecipe": "4",
          "warningAction": {
            "name": "Delete Chicken Noodle Soup",
            "description": "delete the recipe for Chicken Noodle Soup"
          }
        };
        
        this.renderRecipes = this.renderRecipes.bind(this);
        this.deleteRecipe = this.deleteRecipe.bind(this);
      }
      
      deleteRecipe(e) {
        const recipes = Object.assign({}, this.state.recipes);
        const id = e.currentTarget.dataset.id;
        delete recipes[id];
        this.setState({ recipes });
      }
      
      renderRecipes() {
        const recipes = [];
        for (const id in this.state.recipes) {
          recipes.push((
            <tr>
              <td>
                <button type="button" data-id={id} onClick={this.deleteRecipe}
                >&times;</button>
              </td>
              <td>{this.state.recipes[id].name}</td>
            </tr>
          ));
        }
        return recipes;
      }
                    
      render() {
        return (
          <table>
            {this.renderRecipes()}
          </table>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('app'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <main id="app"></main>

    0 讨论(0)
  • 2020-12-06 09:51

    Only way is to create a deep copy and then delete that property from the deep clone and return the deep clone from the setState updater function

    this.setState(prevState => {
                const newState = {
                  formData: {
                    ...prevState.formData,
                    document_details: {
                      ...prevState.formData.document_details,
                      applicant: {
                        ...prevState.formData?.document_details?.applicant
                        keyToBeDeleted: dummVAlue //this is redundant
                      }
                    }
                  }
                };
                delete newState.formData.document_details.applicant.keyToBeDeleted;
                return newState;
              });
    
    0 讨论(0)
提交回复
热议问题