【发布时间】:2021-05-20 00:36:36
【问题描述】:
我有来自控制器的filterData,所以我将filterData 设置为选项,用于UI,
像这样
const [state, setState] = React.useState({
options: filterData,
});
过滤数据是这样的
[{"List": [{"Name": "TEST1", "isSelected": false}, {"Name": "TEST2", "isSelected": false}, {"Name": "TEST3", "isSelected": true}], "Type": "Type"},
{"List": [{"Name": "TEST4", "isSelected": false}, {"Name": "TEST5", "isSelected": false}, {"Name": "TEST6", "isSelected": true}], "Type": "Type2"}]
我将它呈现在flatlist 然后map 列表中,这是我的flatlist 的代码
<FlatList
style={{flex: 1, backgroundColor: colors.white}}
data={state.options}
keyExtractor={(_, index) => index.toString()}
renderItem={({item, index}) => {
return (
<View style={{marginBottom: widthPercentageToDP(5)}}>
<Text>
{item.Type}
</Text>
<View
style={{
flexDirection: 'row',
flexWrap: 'wrap',
}}>
<View
style={{
marginRight: 8,
marginBottom: 8,
}}>
<TouchableOpacity>
<Text>
Select All
</Text>
</TouchableOpacity>
</View>
{item.List.map((e: any, idx: number) => (
<View
key={idx}>
<TouchableOpacity
onPress={() =>
handleSelect(idx, item.Type)
}
>
<Text>
{e.Name}
</Text>
</TouchableOpacity>
</View>
))}
</View>
</View>
);
}}
</View>
</View>
);
}}
/>
正如你从上面看到的,我会有一些buttons。如果点击button,它将调用handleSelect函数。这是这个
const handleSelect = async (idx: number, type: string) => {
let arr = [...state.options];
arr.map((item) => {
if (item.Type === type) {
item.List[idx].isSelected = !item.List[idx].isSelected;
}
});
console.log(state.options)
};
我没有像下面的代码那样改变选项的状态,只有console.log
setState((prevState) => ({
...prevState,
options: arr,
}));
问题是,当我单击并运行该函数时,在日志中,state.options 也会发生变化。
它将具有与arr 相同的数据。即使filterData 也会在我console.log 在handleselect 中发生变化。我已经检查了我的控制器,它没有触发任何功能。
有谁知道为什么它会更新我的所有变量?
【问题讨论】:
标签: javascript typescript react-native mapping use-state