我在我的应用程序中使用React Navigation。返回前一个面板时如何刷新数据?
一个实际的例子是:我目前在Panel A中,我导航到Panel B,在那里我更新了Panel A中显示的数据库中的数据。在更改数据库中的数据后我goBack()到面板 A之后,我希望面板 A现在已经重新渲染并保存数据库中的新数据。
我已经读到我可以将自定义刷新函数作为参数传递给子类并在导航回来之前调用它,但是我认为这不是实现我想要的东西的好方法,因为我更新了一个尚未安装的组件并且我只能抛出错误。
我在我的应用程序中使用React Navigation。返回前一个面板时如何刷新数据?
一个实际的例子是:我目前在Panel A中,我导航到Panel B,在那里我更新了Panel A中显示的数据库中的数据。在更改数据库中的数据后我goBack()到面板 A之后,我希望面板 A现在已经重新渲染并保存数据库中的新数据。
我已经读到我可以将自定义刷新函数作为参数传递给子类并在导航回来之前调用它,但是我认为这不是实现我想要的东西的好方法,因为我更新了一个尚未安装的组件并且我只能抛出错误。
这就是我的成就!
在面板 A
refreshFunction()
{
//your refresh code should be here
}
<TouchableOpacity onPress={()=>{
this.props.navigation.navigate('PanelB', {refreshFunction: this.refreshFunction});
}}>
Redirect to Panel B
</TouchableOpacity>
在面板 B
const refreshFunction = this.props.navigation.state.params.refreshFunction;
if(typeof refreshFunction === 'function')
{
refreshFunction();
//your back function
this.goBack();
}
React Navigation 提供了可用于这种确切场景的侦听器。
例如,将侦听器附加到Panel A,它将在获得焦点时重新获取更新的数据(即,当Panel A “弹回”到时):
componentDidMount() {
const { fetchDatabaseData, navigation } = this.props
fetchDatabaseData()
this.willFocusListener = navigation.addListener(
'willFocus',
() => {
fetchDatabaseData()
}
)
}
componentWillUnmount() {
this.willFocusListener.remove()
}
经过这么多搜索,结论:是的,您可以:
render(){
...
<NavigationEvents
onWillFocus={() => {
//Call whatever logic or dispatch redux actions and update the screen!
}}
/>
...
}
来源:https ://github.com/react-navigation/react-navigation/issues/1171
使用 redux + firebase 我遇到的问题是,在列出该数据的组件返回到 view 之前,来自firebase.on('value', snapshot => { dispatch(data) }
该数据的可观察数据会在保存时更新 redux 存储,因此不会在列表中触发重新渲染。我通过比较过去与当前道具并仅在道具不匹配时重新触发 firebase.on fn 来解决它。这比在导航到列表组件时总是触发要好,但我更喜欢一种在根本不调用 firebase fn 的情况下强制触发重新渲染的解决方案。mappedToProps
onBack()
componentDidUpdate(prevProps) {
if (prevProps.data !== this.props.data) this.props.fetchdata();
}
根据导航事件的导航文档
function Profile({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// do something
});
return unsubscribe;
}, [navigation]);
return <ProfileContent />;
}
如果你有很多这样的场景,你可以使用redux,它可以帮助你跨标签/屏幕和组件管理数据,因为 reduce 连接到 store,在 redux store 中管理整个应用程序状态。