setState仅在一个变量上

时间:2019-03-20 09:29:30

标签: javascript reactjs react-native object setstate

我有一个反应性本机应用程序,状态为:

this.state={
        nameOne:"team 1",
        nameTwo:"team 2",
        pointsForEvents:{
            lap: 1,
            homeRun: 5,
            lyre: 3,
            oneHandCatch: 5,
            burned: 1,
            burnOut: 10,
        }
    }

然后我要更新pointsForEvents中的变量:

<TextInput
        keyboardType="number-pad"
        onChangeText={(lyre) =>{lyre = parseInt(lyre); this.setState({pointsForEvents:{lyre}})}}
        value={this.state.pointsForEvents.lyre+""}
    />

但是setState也会更新“ pointsForEvents”中的其他变量,并且由于未指定值,因此将它们设置为undefined。如何仅更新此一个值。

PS:对象中变量的正确词汇表是什么(例如组件是其子组件的父代)。

2 个答案:

答案 0 :(得分:1)

您可以使用onChangeText = { (lyre) => { lyre = parseInt(lyre); this.setState({ pointsForEvents: { ...this.state.pointsForEvents, lyre, } }) } } 运算符,如下所示:

onChangeText = {
  (lyre) => {
    lyre = parseInt(lyre);
    this.setState((state) => ({
      pointsForEvents: {
        ...state.pointsForEvents,
        lyre,
      }
    }))
  }
}

实际上,此选项会更好:

this.setState

第二个选项更好的原因是因为 apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.tech.usman.securityapp" minSdkVersion 15 targetSdkVersion 28 versionCode 3 versionName "2" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true } buildTypes { /*release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' }*/ release { debuggable false minifyEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } debug { debuggable true minifyEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { pickFirst 'META-INF/LICENSE.txt' // picks the JavaMail license file } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'androidx.appcompat:appcompat:1.0.0-beta01' implementation 'com.google.android.material:material:1.0.0-beta01' implementation 'androidx.constraintlayout:constraintlayout:1.1.2' implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01' implementation 'androidx.vectordrawable:vectordrawable:1.0.0-beta01' implementation 'com.google.firebase:firebase-messaging:17.4.0' implementation 'com.google.firebase:firebase-core:16.0.1' implementation 'com.android.support:appcompat-v7:27.0.1' implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'com.google.android.gms:play-services-location:15.0.1' implementation 'com.android.support:design:27.0.1' implementation 'com.github.ceryle:RadioRealButton:v2.1.1' implementation 'com.android.support:support-v4:27.0.1' implementation 'com.android.support:support-vector-drawable:27.0.1' implementation 'com.jakewharton:butterknife:8.8.1' implementation 'com.google.android.gms:play-services-maps:15.0.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' // retrofit, gson implementation 'com.google.code.gson:gson:2.8.2' implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' //implementation 'com.github.faruktoptas:FancyShowCaseView:1.0.0' //circular progress implementation 'com.github.rahatarmanahmed:circularprogressview:2.5.0' //tray implementation 'net.grandcentrix.tray:tray:0.12.0' implementation('io.socket:socket.io-client:1.0.0') { exclude group: 'org.json', module: 'json' } //http //http looging implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1' //dextor implementation 'com.karumi:dexter:5.0.0' //event bus implementation 'org.greenrobot:eventbus:3.1.1' //rx java implementation 'io.reactivex.rxjava2:rxandroid:2.1.0' implementation 'io.reactivex.rxjava2:rxjava:2.2.0' implementation 'ru.rambler.android:swipe-layout:1.0.15' implementation 'com.android.support:recyclerview-v7:27.0.1' } 不会立即更新状态,因此您可能会看到一些异常情况。

答案 1 :(得分:1)

在您的代码中,您实际上是将pointsForEvents设置为一个新值,这是一个仅包含单个键lyre的对象,因此,其他先前指定的键将不再可用,并解析为{{ 1}}。如果要将其他键保留在对象中,而仅更新键undefined,则必须复制旧对象,仅更新一个键,然后使用该对象设置状态lyre

如答案所示,可以使用散布运算符实现对象的复制。 因此,以下代码创建了一个新对象,其中包含pointsForEvents的所有键以及具有给定值的更新的键lyre,这是您要设置为状态的对象。在这种情况下,pointsForEvents被插入到对象中,但是由于它已经存在,所以只会被更新。

lyre