javascript - 使用导航触发功能组件的刷新(React Native)
问题描述
我的应用程序中的一个屏幕是一个功能组件,如下所示:
export default function DonationsScreen({ navigation }) {
const [requests, setRequests] = useState("")
useEffect(() => {
if (!requests) {
getRequests()
}
}, [])
// I omit some of the code here
return (
<SafeAreaView>
<SearchBar lightTheme placeholder="Type Here..." />
<FlatList
data={requests}
renderItem={({ item }) =>
item.donationsLeft > 0 ? (
<DonationItem request={item} navigation={navigation} />
) : null
}
keyExtractor={(item) => item.id}
/>
</SafeAreaView>
)
}
class DonationItem extends React.Component {
render() {
const { navigate } = this.props.navigation
return (
<Card title="hello">
<Button
buttonStyle={styles.donateButton}
onPress={() =>
this.props.navigation.push("Realizar donación", {
request: this.props.request,
})
}
title="Donar"
/>
</Card>
)
}
}
这样您在 DonationItem 中看到的 onPress 就会导航到另一个名为 DonationFormScreen 的屏幕。此屏幕中的内容并不重要,只是在其中一个方法中调用了另一个导航:
this.props.navigation.push('Donación confirmada', {comingFrom: this.state.comingFrom});
最后,“Donación confirmada”是一个屏幕 DonationConfirmationScreen:
export default class DonationConfirmationScreen extends React.Component {
render() {
return(
<View style={styles.confirmation}>
<View style={styles.confirmationContent}>
<Ionicons name='ios-checkmark-circle' color={'green'} size={130}/>
<Button
buttonStyle={styles.button}
title='Listo'
onPress={() => this.props.navigation.navigate("Pedidos")}
/>
</View>
</View>
);
}
}
如您所见this.props.navigation.navigate("Pedidos")
,在按钮内部调用并且工作正常。
我想要做的不仅是导航回“Pedidos”(这是我的 DonationsScreen),还要触发某种刷新,因为我需要再次调用 getRequests()。我怎样才能做到这一点?
解决方案
感谢所有回答的人,但我最终使用了其他东西,因为我无法让其他东西正常工作。
const isFocused = useIsFocused();
const [requests, setRequests] = useState('');
useEffect(() => {
getRequests();
} , [isFocused])
如您所见,我最终使用了 isFocused。我不得不添加这个导入:
import { useIsFocused } from '@react-navigation/native';
推荐阅读
- java - JPQL 中带有 JPA 的本机查询的“GROUP_CONCAT”是否有替代方案?
- apache-flink - 如何从 Flink 中的 GlobalWindow 中删除现有密钥
- keycloak - Keycloak中“完成注册”信的“欢迎”
- seaborn - 是否可以为通过 lmplot "col" 函数生成的每个图分配颜色?
- python - 如何根据 PageRank 分数对搜索结果进行排序
- elasticsearch - 控制聚合中创建的桶数
- firebase-realtime-database - 一旦时间戳上指示的时间过去,如何使数据不可读?
- php - 我通过 laravel 节点上的 redis 发布(发射),但所有进程都在队列中工作,我想同时运行
- angular - 错误类型错误:您在预期流的位置提供了“未定义”。您可以在 Angular 服务中提供 Observable、Promise、Array 或 Iterable
- javascript - getComputedStyle local vs every time in function Performance