无法在React中更新对象内部状态

时间:2019-06-06 06:00:08

标签: react-native

我是新来的响应本机并尝试更新实际上在对象中并且该对象在状态对象中的变量的人,我尝试了提供的其他解决方案,但是这些解决方案似乎都不在我的代码中。请帮助我确定无论我是在代码中做错什么,还是有其他方法来更新对象的状态,我还添加了在模拟器中显示的实际错误消息。在此先感谢。

constructor(props){
 super(props);
  state={
    firstName:{
      errorName:true,
      firstname:'',
    }
  }
 }
onNameChange=(name)=>{
  this.setState(prevState => {
    let firstName = Object.assign({}, prevState.firstName);       
       firstName.firstname = name;             
        return { firstName }; 
      })
}

<FloatLabel inputStyle={styletheme.inputLabel}
            labelStyle={styletheme.labelInput}
            style={styletheme.formInput}
            onChangeText={(firstname)=> {
                this.onNameChange(firstname)
                }
             }     
>
                   First Name

error message

1 个答案:

答案 0 :(得分:3)

如何使用价差运算符更新值?尝试这样的事情?

constructor(props){
 super(props);
  this.state={
    firstName:{
      errorName:true,
      firstname:'Namrata',
    }
  }
 }
onNameChange=(name)=>{
  //This will make copy of firstName in state and assign it to firstName (read about spread Operator) 
  const firstName = {...this.state.firstName}

  //Once we have made a copy of the property, we are updating the firstName property name 
   firstname.name = name 

   //Now we are storing that new property to this.setState, since we previously made the copy of firstName and then updated that copy, We don't need to use `prevState`
  // setState will set that updated property firstName to the firstName in our this.setState
  this.setState({firstName: firstName })
}

此外,在您的代码中

注释1: 这个return { firstName };似乎是错误的,在您的代码firstName中没有属性firstName。因此,销毁firstName应该给出undefined。如果您想返回,只需return firstName

注意2::您不能仅在构造函数中执行state=,而需要执行this.state=,因为state的作用域仅位于{ {1}}(如果您不使用constructor而使用state

对于this.state中的入门者,如果您进行onNameChange,则应该是未定义的

console.log(this.state)

可能您会将其与构造函数外部的 onNameChange=(name)=>{ console.log(this.state) 混淆

state