我有一個陣列,其中包含我想要呈現的值,然后如果用戶按下編輯按鈕,則演示文稿將更改為 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>
);
}`
我想我的問題與未更新的狀態有關,但是當我按下取消時,我看不到如何保存編輯的值。
uj5u.com熱心網友回復:
問題:
您正在scheduleTempState通過參考您的scheduleState. 所以當你變異時scheduleTempState,它也會變異scheduleState.
解決方案:請使用擴展運算子進行陣列解構,這有助于創建參考的新副本。
const handlePress3 =()=>{
setScheduleTempState([...scheduleState]);
...
}
建議:函式最好使用解釋性名稱。它將使代碼更具可讀性。例如:
onChangeText()代替handlepress()onCancelEditing()代替handlepress2()onEdit代替handlepress3()
希望你能明白這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454506.html
