1

我正在编写一个React + Redux + ReactNative应用程序,它为多个平台( Web、IOS、Android)共享相同的代码。

所以 UI 组件是不同的,但是模型和逻辑在平台之间是共享的。

当我试图导航到一个不同的页面时,我遇到了一个问题,在一个动作中,例如:(我正在使用 react-router 和 react-native-router-flux)

import {browserHistory} from "react-router";
import {Actions} from 'react-native-router-flux'; // This is the problematic import

export function signInSuccessAndRoute(user) {
    if (PlatformInfoShared.isWeb()) {
        const path = '/dashboard';
        browserHistory.push(path);
    } else {
        Actions.mainApplication();
    }
    return signInSuccess(user);
}

问题是,在网上我收到了这个错误:

index.js:1Uncaught SyntaxError:意外的令牌导入

我正在寻找一种作为 If 语句导入的方法,这意味着仅当平台是移动/Web 时才导入,这怎么可能?

或者您可能想到的任何其他选择...谢谢

4

2 回答 2

0

不确定这是否可行,因为我没有在同一个应用程序中将 React Native 与 React 混合(而且我不完全确定 React Native 将如何处理这些导入),但这里有一个想法可能基于以下概念代码拆分:

如果你使用 Webpack2,你可以使用 ES2015 的 System.import 来动态加载你的导入。

if (condition) {
  System.import('moduleName')
    .then(moduleName => {
      moduleName.methodName();
    });
}

如果你在 Webpack1 上, require.ensure 可能会成功。

if (condition) {
  require.ensure(['module-name', 'module-two'], () => {
    const ModuleName = require('module-name');
    const ModuleTwo = require('module-two');
    ModuleName.methodName();
  });
}

注意两者的用法差异。System.import 返回一个承诺。Require.ensure 的第一个参数是一个模块名称数组,第二个参数是一个回调,您可以在其中使用 CommonJS 要求。请注意,回调不需要任何参数。

祝你好运!

于 2016-12-17T22:26:54.907 回答
0

在尝试解决这个问题一段时间后,决定在这里记录它以防其他人遇到同样的问题。

我设法处理这个问题的最好方法是创建一个自定义中间件,一个用于 Web 和移动设备的不同中间件,然后通过操作有效负载进行导航。

移动中间件:

import {Actions} from 'react-native-router-flux';

const ActionableNavigationMobile = store => next => action => {

    if ( ! action.redirect ) return next(action);

    const functionName = action.redirect;

    Actions[functionName]();

    return next(action);

};

export default ActionableNavigationMobile;

网络中间件:

import {browserHistory} from "react-router";

const ActionableNavigation = store => next => action => {

    if ( ! action.redirect ) return next(action);

    const path = action.redirect;
    browserHistory.push(path);

    return next(action);
};

export default ActionableNavigation;

添加为中间件:

export const store = createStore(
    reducer,
    applyMiddleware(thunk,actionableNavigation), //Change this for web and modile stors..
);

行动:

export function signInSuccessAndRoute(user) {
    return dispatch => {
        const redirect = PlatformInfoShared.isWeb() ? "/dashboard" : "mainApplication";
        dispatch(signInSuccess(user));
        dispatch({redirect: redirect});
    };
}
于 2016-12-21T14:58:46.177 回答