programing

React 구성 요소의 상태 개체에서 속성을 제거하려면 어떻게 해야 합니까?

iphone6s 2023. 2. 21. 23:31
반응형

React 구성 요소의 상태 개체에서 속성을 제거하려면 어떻게 해야 합니까?

React 컴포넌트 상태에 속성이 설정되어 있는 경우:

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

★★★★★★★★★를 제거할 수 있습니까?"foo"Object.keys(this.state)

replaceState 메서드는 시행하는 것이 당연해 보이지만 그 이후 권장되지 않습니다.

설정할 수 .foo로로 합니다.undefined 식으로

var Hello = React.createClass({
    getInitialState: function () {
        return {
            foo: 10,
            bar: 10
        }
    },

    handleClick: function () {
        this.setState({ foo: undefined });
    },

    render: function() {
        return (
            <div>
                <div onClick={ this.handleClick.bind(this) }>Remove foo</div>
                <div>Foo { this.state.foo }</div>
                <div>Bar { this.state.bar }</div>
            </div>
        );
    }
});

Example

갱신하다

이전 솔루션에서는 가치 제거만 하면 됩니다.foo스킬이 존재합니다.state를 가 있는state할 수 있는 「」입니다.setState부모 한 명과 같이

var Hello = React.createClass({
  getInitialState: function () {
    return {
      data: {
        foo: 10,
        bar: 10
      }
    }
  },
    	
  handleClick: function () {
    const state = {
      data: _.omit(this.state.data, 'foo')
    };
    
    this.setState(state, () => {
      console.log(this.state);
    });
  },
        
  render: function() {
    return (
      <div>
        <div onClick={ this.handleClick }>Remove foo</div>
        <div>Foo { this.state.data.foo }</div>
        <div>Bar { this.state.data.bar }</div>
      </div>
    );
  }
});

ReactDOM.render(<Hello />, document.getElementById('container'))
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<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>
<div id="container"></div>

var Hello = React.createClass({
getInitialState: function () {
    return {
        foo: 10,
        bar: 10
    }
},

handleClick: function () {
    let state = {...this.state};
    delete state.foo;
    this.setState(state);
},

render: function() {
    return (
        <div>
            <div onClick={ this.handleClick.bind(this) }>Remove foo</div>
            <div>Foo { this.state.foo }</div>
            <div>Bar { this.state.bar }</div>
        </div>
    );
}

});

»ReactCompositeComponent.js 것은 GitHub의 React라고 불리는 입니다._processPendingStateMarge의 setState;setState;setState;

'' _processPendingState: function (function, context) { var inst = 이것._var; var queue = 이것._pendingStateQueue; var replace = 이거._pendingReplaceState ;이것._pendingReplaceState = false(이것)._pendingStateQueue = null;

if (!queue) {
  return inst.state;
}

if (replace && queue.length === 1) {
  return queue[0];
}

var nextState = replace ? queue[0] : inst.state;
var dontMutate = true;
for (var i = replace ? 1 : 0; i < queue.length; i++) {
  var partial = queue[i];
  let partialState = typeof partial === 'function'
    ? partial.call(inst, nextState, props, context)
    : partial;
  if (partialState) {
    if (dontMutate) {
      dontMutate = false;
      nextState = Object.assign({}, nextState, partialState);
    } else {
      Object.assign(nextState, partialState);
    }
  }
}

```

이 코드에서는, 머지를 실장하는 실제의 행을 확인할 수 있습니다.

nextState = Object.assign({}, nextState, partialState);

이 없습니다.delete이기 때문에 완전히 됩니다.또한 setState는 항상 Marge이기 때문에 stat을 완전히 복사하고 속성을 삭제하고 setState를 호출해도 동작하지 않으므로 삭제된 속성은 무시됩니다.

또한 setState는 즉시 동작하지 않지만 배치가 변경되므로 상태 객체 전체를 복제하고 속성 변경을 1개만 수행하려고 하면 이전 콜을 setState로 소거할 수 있습니다.React 문서에 기재되어 있는 바와 같이

React는 성능을 위해 여러 setState() 콜을 단일 업데이트로 일괄 처리할 수 있습니다.

this.props와 this.state는 비동기적으로 갱신될 수 있으므로 다음 상태를 계산할 때 이들 값에 의존해서는 안 됩니다.

실제로 더 많은 정보를 추가할 수 있습니다.

this.setState({ xSet: true, x: 'foo' });
this.setState({ xSet: false, x: undefined });

이것은 보기 흉하지만, 정의되지 않은 값으로 설정된 값과 전혀 설정되지 않은 값을 구별하는 데 필요한 추가 정보를 제공합니다.게다가 React의 내부, 거래, 상태 변경 일괄 처리, 기타 공포와도 잘 어울립니다.트랜잭션 조정, replaceState 등 사용되지 않는 기능 관리 등 공포로 가득 찬 내부 대응에 대해 추측하는 것보다 조금 더 복잡한 방법을 취하는 것이 좋습니다.

사용할 때undefined또는null속성을 제거하기 위해 실제로 제거하지 않습니다.따라서 Javascript 객체의 경우delete속성 앞에 키워드를 입력합니다.

//The original object:
const query = { firstName:"Sarah", gender: "female" };

//Print the object:
console.log(query);

//remove the property from the object:
delete query.gender;

//Check to see the property is deleted from the object:
console.log(query);

다만, 리액트 훅에서는, 훅을 사용하고 있습니다.상기의 방법에서는, 특히 상태가 변화했을 때에 효과를 사용해 무언가를 체크할 때에, 버그가 발생하는 경우가 있습니다.이 경우 속성을 제거한 후 상태를 설정해야 합니다.

import { useState, useEffect } from "react";

const [query, setQuery] = useState({firstName:"Sarah", gender:"female"});
 
//In case we do something based on the changes
useEffect(() => {
    console.log(query);
  }, [query]);

//Delete the property:
delete query.gender;

//After deleting the property we need to set is to the state:
setQuery({ ...query });

이전 솔루션 - this.state를 변경하기 때문에 antiftern입니다.틀렸어!

사용방법(구식) :

let newState = Object.assign({}, this.state) // Copy state
newState.foo = null // modyfy copyed object, not original state
// newState.foo = undefined // works too
// delete newState.foo // Wrong, do not do this
this.setState(newState) // set new state

또는 ES6 설탕을 사용합니다.

this.setState({...o, a:undefined})

꽤 상냥하죠?)

이전 React 구문(ES6이 아닌 원본)에서는 다음과 같이 처리됩니다.this.replaceState불필요한 키를 삭제하지만 현재는 사용되지 않습니다.

를 사용하여 응용 프로그램 상태의 얕은 복사본을 올바른 깊이에서 만들고 복사에서 요소를 삭제할 수 있습니다.그런 다음 를 사용하여 수정된 복사본을 다시 응용프로그램 상태로 병합합니다.

이것은 완벽한 해결책이 아니다.이와 같이 객체 전체를 복사하면 성능/메모리 문제가 발생할 수 있습니다. Object.assign의 얕은 복사는 메모리/퍼포먼스에 대한 우려를 덜어주는 데 도움이 되지만 새로운 오브젝트의 어떤 부분이 복사인지, 어떤 부분이 애플리케이션 상태의 데이터에 대한 참조인지도 알아야 합니다.

다음 예에서는 다음 명령어를 변경합니다.ingredients어레이는 실제로 애플리케이션 상태를 직접 수정합니다.

원하지 않는 요소의 값 설정null또는undefined제거되지 않습니다.

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>

유일한 방법은 딥 복사본을 만든 다음 딥 클론에서 해당 속성을 삭제하고 setState 업데이트 프로그램 함수에서 딥 클론을 반환하는 것입니다.

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;
          });

도트 프로퍼 불변 사용

import dotPropImmutable from "dot-prop-immutable";

onClick() {
    this.setState(
       dotPropImmutable.delete(this.state, 'foo')
    );
}

상태를 완전히 리셋(대부분의 항목을 삭제)하는 경우는, 다음과 같은 조작은 다음과 같습니다.

this.setState(prevState => {
    let newState = {};
    Object.keys(prevState).forEach(k => {
        newState[k] = undefined;
    });
    return newState;
});

이 바리안트의 사용setState를 사용하면 콜 중에 상태 전체에 액세스 할 수 있습니다.this.state(이전 때문에) 약간 구식일 수 있다setState콜이 아직 완전히 처리되지 않았습니다).

이게 좋은 방법인 것 같아 =>

//in constructor
let state = { 
   sampleObject: {0: a, 1: b, 2: c }
}

//method
removeObjectFromState = (objectKey) => {
   let reducedObject = {}
   Object.keys(this.state.sampleObject).map((key) => {
      if(key !== objectKey) reducedObject[key] = this.state.sampleObject[key];
   })
   this.setState({ sampleObject: reducedObject });
}

삭제가 함수 내에 있고 키가 변수여야 하는 경우 다음을 수행합니다.

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

this.removekey('thekey');

스티브의 대답과 거의 비슷하지만, 함수에 있어.

언급URL : https://stackoverflow.com/questions/32884780/how-can-i-remove-an-attribute-from-a-react-components-state-object

반응형