【问题标题】:React Native - React Navigation rerender panel on goBack()React Native - goBack() 上的 React Navigation 重新渲染面板
【发布时间】:2018-09-02 15:16:00
【问题描述】:

我在我的应用程序中使用React Navigation。返回上一个面板时,如何刷新上一个面板上的数据?

一个实际的例子是: 我目前在 Panel A 中,我导航到 Panel B,在那里我更新了显示在 Panel A 中的数据库中的数据。在我 goBack()Panel A 更改数据库中的数据后,我希望 Panel A 现在重新渲染并保存来自数据库。

我已经读到我可以将自定义刷新函数作为参数传递给子类并在返回之前调用它,但是我认为这不是实现我想要的一个简洁的方法,因为我更新了一个尚未更新的组件已安装,我可以抛出一个错误。

【问题讨论】:

  • 你在使用 redux 吗?你说的数据库是什么意思?本地状态或 redux 或 API 调用数据?

标签: react-native refresh react-navigation rerender


【解决方案1】:

这就是我的成就!

在面板 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();
}

【讨论】:

【解决方案2】:

如果你有很多这样的场景,你可以使用redux,它可以帮助你跨标签/屏幕和组件管理数据,因为reduce是连接到存储的,在redux存储整个管理应用程序状态。

【讨论】:

  • 使用 redux 并不能解决问题。
【解决方案3】:

React Navigation provides listeners 可以用于这个确切的场景。

例如,将监听器附加到 Panel A,它会在获得焦点时重新获取更新的数据(即当 Panel A “弹回”到时):

componentDidMount() {
  const { fetchDatabaseData, navigation } = this.props
  fetchDatabaseData()
  this.willFocusListener = navigation.addListener(
    'willFocus',
    () => {
      fetchDatabaseData()
    }
  )
}

componentWillUnmount() {
  this.willFocusListener.remove()
}

【讨论】:

  • 在 Navigation 版本 5 中,我使用了“focus”而不是“willFocus”。这行得通。
【解决方案4】:

经过这么多搜索,结论:是的,您可以:

render(){
...
   <NavigationEvents
      onWillFocus={() => {
      //Call whatever logic or dispatch redux actions and update the screen!
      }}
   />
...
}

来源:https://github.com/react-navigation/react-navigation/issues/1171

【讨论】:

    【解决方案5】:

    使用 redux + firebase 我遇到了问题,来自 firebase.on('value', snapshot =&gt; { dispatch(data) } 的可观察数据是 mappedToProps 会在保存时更新 redux 存储,在列出该数据的组件返回查看 onBack() 之前,所以没有重新render 将在列表中触发。我通过比较过去与当前道具并仅在道具不匹配时重新触发 firebase.on fn 来解决它。这比在导航到列表组件时总是触发要好,但我更喜欢一种在根本不调用 firebase fn 的情况下强制触发重新渲染的解决方案。

      componentDidUpdate(prevProps) {
        if (prevProps.data !== this.props.data) this.props.fetchdata();
      }
    

    【讨论】:

      【解决方案6】:

      根据导航docs 进行导航事件

      function Profile({ navigation }) {
        React.useEffect(() => {
          const unsubscribe = navigation.addListener('focus', () => {
            // do something
          });
      
          return unsubscribe;
        }, [navigation]);
      
        return <ProfileContent />;
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-05
        • 2021-11-26
        • 2023-03-18
        • 1970-01-01
        • 2016-11-09
        • 2021-07-26
        • 2019-09-26
        • 2018-12-27
        • 1970-01-01
        相关资源
        最近更新 更多