为什么不更新值状态未选中的术语



当变量项实际更新并显示在控制台中时,为什么不更新以下组件中未选中的值状态。

在此处查看源和结果

我的方法是存储ID,然后检查数组中是否存在Item ID。

import React, { useState, useEffect } from "react";
import {
StyleSheet,
Text,
View,
CheckBox,
TouchableOpacity
} from "react-native";
const terms = [
{
term_id: 21,
name: "Clothing",
checked: false,
children: [
{
term_id: 24,
name: "Accessories",
checked: false,
children: [
{
term_id: 25,
name: "Scarf",
checked: false,
children: []
},
{
term_id: 22,
name: "Tshirts",
checked: false,
children: []
}
]
}
]
},
{
term_id: 26,
name: "Hodis",
checked: false,
children: []
},
{
term_id: 27,
name: "Socks",
checked: false,
children: []
}
];
export default function Categoris() {
const [unSelectedterms, setSelectionTerms] = useState(terms);
// Adding new state
const [storeIds, setStoreids] = useState([]);
useEffect(() => {}, []);
const setChecked = (data, id) => {
data.map((item) => {
if (item.term_id == id) {
item.checked = !item.checked;
//newTerms.push(item)
}
if (item.children && item.children.length) {
setChecked(item.children, id);
}
});
};
const onchecked = (id) => {
setChecked(terms, id);
setSelectionTerms(terms);
// Checking the existing of the ID
let tempIds = storeIds.map((item) => item);
const isExist = tempIds.findIndex((item) => item === id);
if (isExist === -1) {
tempIds.push(id);
} else {
tempIds = tempIds.filter((item) => item !== id);
}
setStoreids(tempIds);
};
const recursive = (data, level = 0) => {
return data.map((item, key) =>
item.children?.length ? (
<>
{renderItem(level, item.name, item.term_id, item.checked, key)}
{recursive(item.children, level + 1)}
</>
) : (
renderItem(level, item.name, item.term_id, item.checked, key)
)
);
};
// Determine the checked value
const isChecked = (id) => {
const stored = storeIds.map((item) => item);
const tempIndex = stored.findIndex((item) => item === id);
return tempIndex !== -1;
};
const renderItem = (level, name, id, checked, key) => (
<TouchableOpacity
style={{ flexDirection: "row", alignItems: "center" }}
key={id}
onPress={() => {
onchecked(id);
}}
>
<CheckBox
// Using the determine function
value={isChecked(id)}
onValueChange={() => {
onchecked(id);
}}
/>
<Text style={{ fontWeight: "bold" }}>
{level > 0 && " -".repeat(level)} {name}
</Text>
</TouchableOpacity>
);
return <View style={styles.container}>{recursive(unSelectedterms)}</View>;
}
const styles = StyleSheet.create({
item: {
fontSize: 20
},
container: {
backgroundColor: "#fff",
padding: 50
}
});

最新更新