【问题标题】:React-native: Axios not working on ios but working on android. Error: JSON Value '<null>' of type NSNull cannot be converted to NSStringReact-native:Axios 不在 ios 上工作,但在 android 上工作。错误:NSNull 类型的 JSON 值“<null>”无法转换为 NSString
【发布时间】:2018-04-22 06:21:09
【问题描述】:

我运行了调试器,但 axios 发送请求失败。同样的事情在Android中也能完美运行。一旦它通过 axios 发送请求,模拟器上就会弹出这些红色屏幕:

这是给出错误的代码:

 /*red screen here after request send*/return axios.get(config.backend_url + '/api/firebase-user/' + firebaseId)
          .then((userDataFetchResult) => {
            dispatch(setUserGeneralData(userDataFetchResult.data.data));
            dispatch(authOperationFinished());
            return userData;
          })
          .catch(err => {
            console.log(err);
            dispatch(authOperationFailed(err));

          });

我的 package.json:

 "dependencies": {
    "axios": "^0.18.0",
    "lodash": "^4.17.5",
    "native-base": "^2.4.1",
    "react": "16.3.1",
    "react-native": "0.54.1",
    "react-native-app-intro-slider": "^0.2.4",
    "react-native-datepicker": "^1.7.1",
    "react-native-fbsdk": "^0.7.0",
    "react-native-firebase": "^4.0.0",
    "react-native-image-picker": "^0.26.7",
    "react-native-navigation": "^1.1.444",
    "react-native-twitter-signin": "^1.0.2",
    "react-native-vector-icons": "^4.6.0",
    "react-redux": "^5.0.6",
    "redux": "^3.7.2",
    "redux-thunk": "^2.2.0"
  }

我的 info.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fbXXXXXXX</string>
            </array>
        </dict>
    </array>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>fbapi</string>
        <string>fb-messenger-share-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
    </array>
    <key>NSCameraUsageDescription</key>
    <string>Camera Permissions</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>Gallery Permissions</string>
    <key>UIAppFonts</key>
    <array>
        <string>Ionicons.ttf</string>
    </array>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>FFFF</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <false/>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string></string>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>
    <key>FacebookAppID</key>
    <string>XXXXXX</string>
    <key>FacebookDisplayName</key>
    <string>FF</string>
</dict>
</plist>

我的 AppDelegate.m:

#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>

// **********************************************
// *** DON'T MISS: THE NEXT LINE IS IMPORTANT ***
// **********************************************
#import <TwitterKit/TwitterKit.h>

// IMPORTANT: if you're getting an Xcode error that RCCManager.h isn't found, you've probably ran "npm install"
// with npm ver 2. You'll need to "npm install" with npm 3 (see https://github.com/wix/react-native-navigation/issues/1)

#import <Firebase.h>
#import "RCCManager.h"

#import <React/RCTRootView.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [FIRApp configure];

  [[FBSDKApplicationDelegate sharedInstance] application:application
                           didFinishLaunchingWithOptions:launchOptions];


  NSURL *jsCodeLocation;
#ifdef DEBUG
  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  self.window.backgroundColor = [UIColor whiteColor];
  [[RCCManager sharedInstance] initBridgeWithBundleURL:jsCodeLocation launchOptions:launchOptions];

  return YES;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<NSString *,id> *)options {

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
                                                                openURL:url
                                                      sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                                             annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
                  ];

  BOOL handledT = [[Twitter sharedInstance] application:application openURL:url options:options];
  // Add any custom logic here.
  return handled || handledT;
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
  [FBSDKAppEvents activateApp];
}

@end

知道可能是什么问题吗?非常感谢!

编辑:显然请求数据到达,但无论如何它都会抛出红屏。调用它的组件的渲染方法在抛出错误之前也会运行多次。我在 componentDidMount 上调用它。渲染方法是

render() {

    let content = (
      <CausesList
        causes={this.props.causes}
        onItemSelected={this.itemSelectedHandler}
        onLoadMore={this.onLoadMoreHandler}
      />
    ); 


    let spinner = null;

    if (this.props.causesFetchLoading || this.state.checkingFirebaseAuth) {
      spinner = <ActivityIndicator />
    }

     return (
      <View>
           <SearchBar onSearch={this.onShearchHandler} />
           <CauseCategoriesList causeCategories={this.props.causeCategories} onCategoryPressed={this.onCategoryPressedHandler} /> 
          {content}
          {spinner}
      </View>
    );
  }
}

编辑 2:这似乎与网络无关。我一直在使用调试器跟踪程序,但它在渲染组件时失败了。它必须进行一些在 android 中被接受但在 ios 中不被接受的转换......

【问题讨论】:

    标签: ios react-native axios react-native-ios


    【解决方案1】:

    我通过调试器的大量挖掘解决了这个问题,因为错误消息非常神秘而且根本没有帮助。遗憾的是它没有显示更具体的内容。

    最后,这与网络无关。数据到达但在渲染时失败。我开始一次删除一个组件以查看问题可能是什么,直到问题指向具有 图像组件卡片组件

    问题在于,如果您在 React Native 中使用 null 值设置图像的来源,Android 将毫无问题地接受它。但是如果你在 IOS 中这样做,那么它会抛出你在上面看到的错误(红屏)。

    解决方案是如果路径不为空,则有条件地渲染图像。以下是我如何解决它以供将来参考:

    if(props.cause.pic_url){
        image = (<Image source={{uri: props.cause.pic_url}} style={{height: 200, width: 200, flex: 1}}/>)
    
      }
    
      return (<TouchableOpacity onPress={props.onItemPressed}>
        <Card style={{flex: 0}}>
                <CardItem>
                  <Left>
                      { thumbnail }
                    <Body>
                    <Text>{props.cause.name}</Text>
                    <Text>{props.cause.hashtag}</Text>                  
                    </Body>
                  </Left>
                </CardItem>
                <CardItem>
                  <Body>
                       { image }
                    <Text>
                      {props.cause.short_description}
                    </Text>
                  </Body>
                </CardItem>
                <CardItem>
                  <Left>
                    <Button transparent textStyle={{color: '#87838B'}}>
                      <Icon name="logo-github" />
                      <Text>1,926 stars</Text>
                    </Button>
                  </Left>
                </CardItem>
              </Card>
    
      </TouchableOpacity>)
    

    【讨论】:

      猜你喜欢
      • 2019-05-02
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多