作為調查的一部分,我有一個供用戶完成的問題串列,我將這些問題呈現在所有位于父檔案中的不同組件中。我能夠從狀態中更新的子組件中獲取每個值,但現在想要更新我在當前設定為 Null 的 JSON 物件中的 Answer 欄位。
這是我的 JSON 物件,稱為 data

我需要訪問每個問題并更新該answer欄位。
我的父檔案目前看起來像這樣:
export default function SurveyScreen({navigation, route}) {
const [childNameValue, setChildNameValue] = useState('');
const updateQuestion = (answer, type_index, question_index) => {
console.log(answer);
};
return (
<ScrollView style={styles.cardContainer}>
<View>
<Text style={styles.title}>Please fill out all questions below</Text>
</View>
<View>
<BasicTextInput
title="Child's full name"
value={childNameValue}
onChangeValue={newValue => setChildNameValue(newValue)}
updateQuestion(newValue);
/>
);
}
和子組件檔案:
export default function BasicTextInput({title, onChangeValue, updateQuestion}) {
return (
<View style={styles.container}>
<View style={styles.containerHeader}>
<Text style={styles.questionTitle}>{title}</Text>
</View>
<View style={styles.answerContainer}>
<TextInput
style={styles.input}
onChangeText={onChangeValue}
updateQuestion={updateQuestion}
/>
<View />
</View>
</View>
);
}
我在我的父組件中得到了答案并成功運行了 console.log(answer)。
我希望能夠在運行 axios 請求以提交它之前更新 JSON 物件中的答案欄位。
我認為在我的 updateQuestion 函式中運行類似的東西可能會起作用,但想知道最好的方法是什么?
data.questions[type_index].questions[question_index].answer.answer = answer;
先感謝您!
uj5u.com熱心網友回復:
您當然可以改變要更新的欄位。
或者,您可以使用 React 能夠檢測到的適當的不可變更新:
// something like
const replace = (arr, i, insert) => [...arr.slice(0, i), insert, ...arr.slice(i 1)];
const updateDeepDeepAnswer = {
...data,
questions: replace(data.questions, type_index, {
... data.questions[type_index],
questions: replace(data.questions[type_index].questions, question_index, {
...data.questions[type_index].questions[question_index],
answer: {
...data.questions[type_index].questions[question_index].answer,
answer,
},
}),
}),
}
這就是為什么我們試圖在 React 狀態下盡可能保持資料簡單。
我很想:
- 將問題集和問題存盤在單獨的狀態切片上。所以對答案欄位的更新不是深度更新。
- 單獨存盤答案及其問題 ID。然后將這些 questionId answer 物件發送到您的 api 以保存在資料庫中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/359563.html
上一篇:使用HooksAPI:React是否尊重setState順序?
下一篇:com.facebook.react.bridge.readablenativemap無法在ReactNative中轉換為java.lang.string
