![](/img/trans.png)
[英]Items in grid are not updating after I update the useState in react native applcation
[英]useState is not updating even after the value that trigger the update changes React Native
我正在嘗試將對象附加到 Firestore。 添加到 Firestore 的方法是檢查對象的鍵。 例如,“Electronics1”是文檔中存在的對象的鍵,然后將最后一位數字加 1 並附加到文檔中,即“Electronics2”。 我的問題是我使用 setIndex useState 來記錄文檔中的最大數字。 但是,第一次,即使“值”發生變化,索引也將始終為 0。 每當下拉列表中的值發生變化時,如何使其更新?
const [index, setIndex] = useState(0);
useEffect(() => {
let isCancelled = false;
async function dataToAdd() {
if (value !== null) {
const charLen = value.length;
const docRef = doc(db, 'users', auth.currentUser.uid, 'expense', value);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
const singDocRec = docSnap.data();
let num = 0;
Object.entries(singDocRec).map(([key, record]) => {
if (key != null || key != '' || key != undefined) {
let i = key.slice(charLen, key.length);
if (i > num) {
num = i;
}
}
});
if (!isCancelled) {
setIndex(parseInt(num) + 1);
}
}
}
}
dataToAdd();
return () => {
isCancelled = true;
};
}, [value]);
const createObj = value => {
const concatStr = value.concat(index.toString());
let obj = {};
obj[concatStr] = {title: title, date: date, category: value};
return obj;
};
<DropDownPicker
style={{
borderRadius: 0,
}}
open={open}
value={value}
items={items}
setOpen={setOpen}
setValue={setValue}
setItems={setItems}
/>
<TouchableOpacity
onPress={() => {
addFunc(value, createObj(value));
navigation.navigate('Home');
}}
style={{
width: 300,
height: 50,
marginTop: 20,
borderWidth: 2,
justifyContent: 'center',
}}>
<Text style={{textAlign: 'center', color: 'black', letterSpacing: 2}}>
CONFIRM
</Text>
</TouchableOpacity>
為什么不嘗試在 onChangeValue 或 onSelectItem 中調用 useEffect 中的所有函數? onChangeValue={(value) => { callTheFunctionhere() }}
嚴格的不等式運算符是用 JavaScript 編寫的!==
:
試試: if (key !== null || key !== '' || key !== undefined)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.