使用 React Navigation 导航堆栈时重新渲染组件 [英] Re-render component when navigating the stack with React Navigation

查看:48
本文介绍了使用 React Navigation 导航堆栈时重新渲染组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 react-navigation 进行堆栈和选项卡导航.

I am currently using react-navigation to do stack- and tab- navigation.

是否可以在用户每次导航到特定屏幕时重新渲染组件?我想确保每次到达特定屏幕时都重新运行 componentDidMount(),因此我通过调用适当的操作创建者从服务器获取最新数据.

Is it possible to re-render a component every time the user navigates to specific screens? I want to make sure to rerun the componentDidMount() every time a specific screen is reached, so I get the latest data from the server by calling the appropriate action creator.

我应该考虑哪些策略?我很确定这是一种常见的设计模式,但我没有看到记录的示例.

What strategies should I be looking at? I am pretty sure this is a common design pattern but I failed to see documented examples.

推荐答案

React Navigation 生命周期事件 引用自 反应导航

React Navigation 向订阅它们的屏幕组件发出事件.您可以订阅四种不同的事件:willFocus、willBlur、didFocus 和 didBlur.在 API 参考中阅读有关它们的更多信息.

React Navigation emits events to screen components that subscribe to them. There are four different events that you can subscribe to: willFocus, willBlur, didFocus and didBlur. Read more about them in the API reference.

让我们看看这个,

使用 导航监听器 您可以在页面中添加一个事件监听器,并在每次页面获得焦点时调用一个函数.

With navigation listeners you can add an eventlistener to you page and call a function each time your page will be focused.

const didBlurSubscription = this.props.navigation.addListener(
  'willBlur',
  payload => {
    console.debug('didBlur', payload);
  }
);

// Remove the listener when you are done
didBlurSubscription.remove();

替换 payload 函数并用您的刷新"函数更改它.

Replace the payload function and change it with your "refresh" function.

希望这会有所帮助.

这篇关于使用 React Navigation 导航堆栈时重新渲染组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆