简体   繁体   English

反应-检查对象是否处于状态变量

[英]React - check if a object is in state variable

I have a state variable that is a object (called testObject). 我有一个状态变量,它是一个对象(称为testObject)。 I store several objects in that state variable. 我在该状态变量中存储了几个对象。 Iam looking for a way to check if a object already exists in that state variable then remove it if true. 我正在寻找一种检查对象的状态变量中是否存在的方法,如果为true,则将其删除。

so to sum up the dilemma: 总结一下困境:

  • check if a object is already in testObject 检查对象是否已经在testObject中
  • If true => delete that object 如果为true =>删除该对象
  • if false => add the object to testObject 如果为false =>将对象添加到testObject

    class Connector extends Component { 类Connector扩展Component {

     constructor(props) { super(props); this.state=({ testObject: {}, }); console.log(this.props); } 

    } }

How about toggling the state? 如何切换状态?

this.setState(prevState => ({
  testObject: {
    ...prevState.testObject,
    someProperty: !prevState.testObject.someProperty
  }
}))

You can check it by this way: 您可以通过以下方式进行检查:

if (this.state.testObject.hasOwnProperty(property_name))
  delete this.state.testObject.property_name
else {
  var testObject = this.state.testObject
  testObject[property_name] = some_value
  this.setState({testObject: testObject})
}

This code will delete the testObject key from the state if present. 如果存在,此代码将从状态中删除testObject键。

Assuming that obj is the object you want to delete/add. 假设obj是您要删除/添加的对象。

let newState = this.state.testObject

if (this.state.testObject.obj) {
    delete newState["obj"]
} else {
    newObject["obj"] = "value"
}

this.setState({ testObject: newState })

if the obj is present in testObject, then it will delete it, else it will insert obj in testObject. 如果obj存在于testObject中,则它将删除它,否则它将obj插入testObject中。

lets say the object in question is in testObject with key obj and the incoming var is newTestObj. 假设有问题的对象在testObject中,键为obj,传入的var为newTestObj。

then we will check 然后我们将检查

if(this.state.testObject && this.state.testObject.obj) {
   let tempObj = this.state.testObject;
   delete tempObj.obj;
   this.setState({
      testObject: tempObj
   })
}else {
  this.setState({
      testObject: {...testObject, obj: newTestObj.obj}
   })
}

use an if statement to check if the object exists. 使用if语句检查对象是否存在。

if(this.state.objectName)
  delete this.state.objectName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM