我有一个项目列表,当单击一个项目时,它会导航到一个显示选项列表的模式。我试图增加每个选项内的计数器,它按预期工作但是当我退出模式屏幕并返回它时,选项计数器不会重置。
const myOptions = [
{ id: '001', name: 'option 001', counter: 0 },
{ id: '002', name: 'option 002', counter: 0 },
];
function ModalScreen({ route, navigation }) {
const [options, setOptions] = useState(myOptions);
let tempArr = [...myOptions];
// Array where I increment the counter, before passing it to setOptions(tempArr)
useEffect(() => {
return () => {
// because of let tempArr = [...myOptions]; changes in tempArr are copied
in myOptions. I want to reset myOptions when I exit the component
console.log(options);
console.log(myOptions) // both output are identical
};
}, []);
return (
<View>
<Text style={{ fontWeight: 'bold', marginBottom: 15 }}>
Click on an option to increment counter by 1
</Text>
<FlatList
keyExtractor={item => item.name}
extraData={tempArr}
data={options}
renderItem={({ item, index }) => (
<TouchableOpacity
onPress={() => {
tempArr[index].counter++;
setOptions(tempArr);
}}>
<Text>
{item.name} - counter: {item.counter}
</Text>
</TouchableOpacity>
)}
/>
</View>
);
}
我在这里做了一个演示:https : //snack.expo.io/@oliviermtl/carefree-marshmallows
我花了一整天的时间试图弄清楚这个......如果需要更多解释,请告诉我谢谢
改变
useEffect(() => {
return () => {
console.log(options);
console.log(myOptions)
};
}, []);
到
useEffect(() => {
return () => {
myOptions[0].quantity = 0;
myOptions[1].quantity = 0;
};
},[]);
我所做的是将数量值更改为 0,无论何时用户关闭或从模态中退出。希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句