在 React Native 组件中更新状态的问题

Problem with updating state in react native component

我有一个包含我想要呈现的值的数组,然后如果用户按下编辑按钮,则呈现将更改为 TextInput 组件列表。完成编辑后,用户可以按保存或取消。如果按下取消,textInput 字段中的值不应保存到原始值数组。

我的问题是,即使按下取消,原始数组中的数据似乎也已更新。

这是代码:

`

const handlePress = (text, index) => {
    const newSchedule = [...scheduleTempState]
    newSchedule[index].value = text
    setScheduleTempState(newSchedule)
  }


  const handlePress2 =()=>{
    setScheduleTempState([]); 
    console.log("handlepress2")
    setEdit(false)
   }  
  
   const handlePress3 =()=>{
    setScheduleTempState(scheduleState); 
    console.log("handlepress3")
    setEdit(true)
   }  
  

return (
    edit
    ?
    <View style={styles.scheduleRow}>
        <View style={styles.buttonView}>
            <TouchableOpacity onPress = { ()=>{saveSchedule(projectId,scheduleState);updateClient() ;setEdit(false)}} >  
                <MaterialIcons name="save" size={16} color="green" />
            </TouchableOpacity>
            <TouchableOpacity onPress = { ()=>{handlePress2()}} >  
                <MaterialIcons name="cancel" size={16} color="red" />
            </TouchableOpacity>
        </View>
       <View>
        <FlatList
            horizontal = {true}
            data={scheduleTempState}
            keyExtractor={item => item.id}
            renderItem={({item, index}) => {
            return (
                <View style={styles.decimalInputView}>
                    <TextInput 
                        style={styles.cellInput}    
                        onChangeText={(text) => {handlePress(text, index)}} 
                        value = {item.value} />
                </View>
                )
            }}
        />  
        </View>        
    
    </View>
    :
    <View style={styles.scheduleRow}>
        <View style={styles.buttonView}>
            <TouchableOpacity onPress = { ()=>handlePress3()} >  
                <MaterialIcons name="edit" size={14} color="black" />
            </TouchableOpacity>
        </View>
        <View >
           <FlatList
            horizontal={true}
            data={scheduleState}
            renderItem={renderScheduleItem}
            keyExtractor={item => item.id}
          />
        </View>
      
    </View>
);

}`

我想我的问题与未更新的状态有关,但我看不到当我按下取消时如何保存编辑的值。

问题: 您正在通过引用 scheduleState 来更新 scheduleTempState。所以当你改变 scheduleTempState 时,它也会改变 scheduleState.

解决方法:请使用扩展运算符scheduleState,这有助于创建引用的新副本。

const handlePress3 =()=>{
    setScheduleTempState([...scheduleState]);
    ...
}

建议:函数最好使用解释性名称。它将使代码更具可读性。例如:

  1. onChangeText() 而不是 handlepress()
  2. onCancelEditing() 而不是 handlepress2()
  3. onEdit 而不是 handlepress3()

希望你能明白。