11

我正在使用 ReactNavigation 并且想知道如何判断视图何时出现(以便我可以触发数据刷新)。我看到这个示例使用不同的导航器 NavigatorIOS - 是否有 viewDidAppear 或 viewWillAppear 等效项?但不确定它如何与https://reactnavigation.org/一起使用。

我在导航调度上看到了 console.log - 但是是否有一些事件处理程序可以挂接到屏幕/组件级别以了解该组件/屏幕是否在前台?我应该getStateForAction以某种方式挂钩该方法吗? https://reactnavigation.org/docs/routers/api。我不想真正创建自定义路由处理程序本身,只是为了检测视图是否进入前台/是否会出现,我猜我可以使用导航事件以某种方式做到这一点。

4

3 回答 3

4

因此,我通过创建一个跟踪活动屏幕并将其附加到根导航onNavigtionChange事件的 redux 操作和存储来完成这项工作。

      <RootNavigation
        ref={nav => { this.navigator = nav; }}
        onNavigationStateChange={(prevState, currentState) => {
          const currentScreen = this.getCurrentRouteName(currentState);
          const prevScreen = this.getCurrentRouteName(prevState);
          if (prevScreen !== currentScreen) {
            this.props.broadcastActiveScreen(currentScreen);
            {/*console.log('onNavigationStateChange', currentScreen);*/}
          }
        }}
      />

行动

import { createAction } from 'redux-actions';
import type { Dispatch } from '../state/store';

export const SCREEN_WILL_APPEAR = 'SCREEN_WILL_APPEAR';
const createScreenWillAppearAction = createAction(SCREEN_WILL_APPEAR);
export const broadcastActiveScreen = (activeScreen: string) => (
  (dispatch: Dispatch) => {
    dispatch(createScreenWillAppearAction(activeScreen));
  }
);

减速器

export default handleActions({
  [SCREEN_WILL_APPEAR]: (state, action) => {
    return Object.assign({}, state, {
      activeScreen: action.payload,
    });
  },
}, initialState);

在屏幕组件中

  componentWillReceiveProps(nextProps) {
    if (nextProps.activeScreen === 'MyScreenName' && nextProps.activeScreen !== this.props.activeScreen) {
     // put your on view will appear code here
    }
   }
于 2017-05-23T14:38:04.730 回答
3

我认为didFocus,willFocus和events 将满足您的需求didBlurwillBlur

您需要在componentWillMountandcomponentWillUnmount方法中设置/取消设置它们。

请参阅此处此处的文档。这些例子不是最好的。如果你想要一个例子,请随时询问!

于 2018-08-29T13:04:29.593 回答
1

使用React Navigation时,您将组件作为屏幕提供。你可以在里面处理你想要的东西。这些是反应组件,所以它们有componentWillMountcomponentDidMount。最好使用componentDidMount因为它不会阻塞渲染。

对于第一次渲染组件,componentDidMount是一个不错的选择。下次,您应该使用componentWillReceiveProps。当组件再次渲染时调用此函数。

update: 如果 props 没有改变,componentWillReceiveProps不会被触发。我认为它发生在你的情况下。您应该编写自定义路由器或使用计时器以间隔触发。

于 2017-04-15T03:23:15.783 回答