我正在尝试创建一个民意调查投票页面,点击其中一个选项应将其计数增加 1。
这是我到目前为止所拥有的:
import { FlatList, SafeAreaView, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import FontAwesome from "react-native-vector-icons/FontAwesome"
export function PollDetailsScreen({ route }) {
const { pollQuestion, pollOptions } = route.params;
const renderItem = ({ item }) => {
return (
<TouchableOpacity
onPress={() => {
pollOptions.map(option => {
if (option.key === item.key) {
option.optionCount + 1
}
})
}}
style={{ paddingTop: 32 }}
>
<View style={styles.item}>
<Text style={{ fontSize: 20 }}>{item.newOption}</Text>
<Text>{item.optionCount} vote{item.optionCount > 1 ? 's' : ''} <FontAwesome name="check-circle" size={24} color="#617A67" /></Text>
</View>
</TouchableOpacity>
);
}
return (
<View style={styles.container}>
<Text style={{ fontSize: 24 }}>{pollQuestion}</Text>
<SafeAreaView>
<FlatList
data={pollOptions}
renderItem={renderItem}
keyExtractor={item => item.key}
extraData={pollOptions} />
</SafeAreaView>
</View>
)
}
pollOptions
对象数组看起来像这样:
pollOptions: [
{
key: "839f2h9",
newOption: "Pasta",
optionCount: 0
},
{
key: "1v1wuw1",
newOption: "Pizza",
optionCount: 0
},
{
key: "95823hc",
newOption: "Kebab",
optionCount: 0
}
]
现在的问题是点击其中一个选项不会更新票数。我应该使用
useEffect
来更新 Flatlist
的状态还是应该如何处理?
您需要将 pollOptions 和 pollQuestions 放入 useState 中,因为您希望其更改导致重新渲染。
const [pollOptionsState,setPollOptionsState] = useState(pollOptions)
const [pollQuestionsState,setPollQuestionsState] = useState(pollQuestions)
更新啦
setPollOptionsState (prev => {
// do logic here
const newOpts = prev.filter(x=>...)
return newOpts
})
或者,你可以设置Prams
const navigation = useNavigation()
const update () => {
navigation.setParams(...)
}