React NativeReact Native开发javascript

翻译|React-navigation导航系统(3)-高级指南

2017-03-29  本文已影响4464人  smartphp

title: 翻译|React-navigation导航系统(3)-高级指南
date: 2017-03-29 16:41:19
categories: 翻译
tags: React-Native


Redux Intergration

为了在redux中处理app的navigation state,你可以传递你自己的navigation prop到一个navigator.你的navigation prop必须提供当前的state,还有就是处理navigation配置项的dispatcher.

使用redux,你的app state由reducer来定义.每一个navigation router都有一个reducer,叫做getStateForAction.下面是一在redux应用中使用navigators的简单实例:

import { addNavigationHelpers } from 'react-navigation';

const AppNavigator = StackNavigator(AppRouteConfigs);

const navReducer = (state, action) => {
  const newState = AppNavigator.router.getStateForAction(action, state);
  return newState || state;
};

const appReducer = combineReducers({
  nav: navReducer,
  ...
});

@connect(state => ({
  nav: state.nav,
}))
class AppWithNavigationState extends React.Component {
  render() {
    return (
      <AppNavigator navigation={addNavigationHelpers({
        dispatch: this.props.dispatch,
        state: this.props.nav,
      })} />
    );
  }
}

const store = createStore(appReducer);

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <AppWithNavigationState />
      </Provider>
    );
  }
}

一旦按照实例操作,navigation state就存储在redux的store中,这样就可以使用redux的dispatch函数来发起navigation的actions.

牢记在心,当一个navigator给定一个navigationprop,他将失去内部state的控制权.这意味着现在你来负责state的持久化,处理任何的深度链接,整合Back按钮等操作.

当你的navigator是巢式的时候,Navigation state自动从一个navigator传递到另一个navigator.注意,为了让子代navigator可以从父代navigator接收state,它应该定义为一个screen.

对应上面的实例,你可以定义AppNavigator包含一个巢式的TabNavigator:

 const AppNavigator = StackNavigator({
  Home: { screen: MyTabNavigator },
});

在这个实例中,一旦你在AppWithNavigationStateconnect AppNavigator到Redux,MyTabNavigation将会自动接入到navigation state 作为navigtion的prop.

Web Integration

React Navigation routers工作在web环境下允许你和原生app共享导航的逻辑.绑定在react-navigation的视图目前只能工作在React Native下,但是在react-primitives项目中可能会有所改变.

示例程序

这个网站由React Navigation构建,使用了createNavigationTabRouter.
看看网站的源代码app.js

app如何获得渲染参看server.js.在浏览器中,使用[BrowserAppContainer.js]来唤醒和获得渲染.

更多内容,很快呈现

不久会有详细的教程.

Deep Linking

这一部分指南中,我们将设置app来处理外部URIs.让我们从SimpleApp开始
getting start的指南

在这个示例中,我们想使用类似mychat://chat/Taylor的URI来打开我们的app,直接连接到Taylor的chat page.

Configuration

在前面我们定义了navigator想下面这样:

 const SimpleApp = StackNavigator({
  Home: { screen: HomeScreen },
  Chat: { screen: ChatScreen },
});

我们想让path类似chat/Taylor链接到“Chat”screen,传递user作为参数.我们重新定义我们的chat screen使用一个path来告诉router需要匹配的path和需要提取的参数.这个路径配置为chat/:user.

 const SimpleApp = StackNavigator({
  Home: { screen: HomeScreen },
  Chat: {
    screen: ChatScreen,
    path: 'chat/:user',
  },
});

URI的前缀

下面配置navigation container来提取app的path.当配置在顶层navigator上的时候,我们提供containerOperations,

 const SimpleApp = StackNavigator({
  ...
}, {
  containerOptions: {
    // on Android, the URI prefix typically contains a host in addition to scheme
    URIPrefix: Platform.OS == 'android' ? 'mychat://mychat/' : 'mychat://',
  },
});

iOS

基于mychat://URI图式配置原生的iOS app.
SimpleApp/ios/SimpleApp/AppleDelegate.m

 // Add the header at the top of the file:
#import <React/RCTLinkingManager.h>

// Add this above the `@end`:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}

在Xcode里,打开项目的simpleApp/ios/SimpleApp.xcodeproj.在边栏中选择项目导航到info tab.向下滑动到“URL Types”并且添加一个.在新的URL type,设定名称和url图式对应想导航到的url图式.

现在可以在Xcode中点击play,或者在命令行运行

react-native run-ios

为了在iOS中测试URI,在safari中打开mychat://chat/Taylor

Android

为了在Andorid中链接外链,可以在manifest中创建一个新的intent.
SimpleApp/android/app/src/main/AndroidManifest.xmlMainActivity内添加新的VIEWtypeintent-filter.

 <intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="mychat"
          android:host="mychat" />
</intent-filter>

现在,重新运行:

 react-native run-android

在Android中测试intent操作,运行

 adb shell am start -W -a android.intent.action.VIEW -d "mychat://mychat/chat/Taylor" com.simpleapp

Screen tracking and analytics

这个实例中展示怎么做屏幕追踪并且发到Google Analytics.这个方法应用在其他的移动分析SDK也是可以的.

Screen tracking

当我们使用内建的navigation container,我们使用onNavigationStateChange来追踪screen.

 import { GoogleAnalyticsTracker } from 'react-native-google-analytics-bridge';

const tracker = new GoogleAnalyticsTracker(GA_TRACKING_ID);

// gets the current screen from navigation state
function getCurrentRouteName(navigationState) {
  if (!navigationState) {
    return null;
  }
  const route = navigationState.routes[navigationState.index];
  // dive into nested navigators
  if (route.routes) {
    return getCurrentRouteName(route);
  }
  return route.routeName;
}

const AppNavigator = StackNavigator(AppRouteConfigs);

export default () => (
  <AppNavigator
    onNavigationStateChange={(prevState, currentState) => {
      const currentScreen = getCurrentRouteName(currentState);
      const prevScreen = getCurrentRouteName(prevState);

      if (prevScreen !== currentScreen) {
        // the line below uses the Google Analytics tracker
        // change the tracker here to use other Mobile analytics SDK.
        tracker.trackScreenView(currentScreen);
      }
    }}
  />
);

使用Redux做Screen tracking

使用Redux的时候,我们可以写Redux 中间件来track screen.为了达到这个目的,我们从前面的部分重新使用getCurrenRouteName.

 import { NavigationActions } from 'react-navigation';
import { GoogleAnalyticsTracker } from 'react-native-google-analytics-bridge';

const tracker = new GoogleAnalyticsTracker(GA_TRACKING_ID);

const screenTracking = ({ getState }) => next => (action) => {
  if (
    action.type !== NavigationActions.NAVIGATE
    && action.type !== NavigationActions.BACK
  ) {
    return next(action);
  }

  const currentScreen = getCurrentRouteName(getState().navigation);
  const result = next(action);
  const nextScreen = getCurrentRouteName(getState().navigation);
  if (nextScreen !== currentScreen) {
    // the line below uses the Google Analytics tracker
    // change the tracker here to use other Mobile analytics SDK.
    tracker.trackScreenView(nextScreen);
  }
  return result;
};

export default screenTracking;

创建Redux store并应用上面的中间件

在创建store的时候应用这个screenTracking的中间件.看看Redux Integration了解细节.

 const store = createStore(
  combineReducers({
    navigation: navigationReducer,
    ...
  }),
  applyMiddleware(
    screenTracking,
    ...
    ),
);
上一篇下一篇

猜你喜欢

热点阅读