React Native:无法连接到开发服务器

6

我有一个非常简单的React Native项目,想要让它正常运行。这是一个iOS项目,只需要将RCTRootView添加到UIViewController即可。当我从Xcode运行应用程序时,出现了红屏错误:

Could not connect to development server.

Ensure the following:
- Node server is running and available on the same network - run 'npm start' from react-native root
- Node server URL is correctly set in AppDelegate

AppDelegate.h

@property (strong, nonatomic) RCTRootView *rootView;

AppDelegate.m在application:didFinishLaunchingWithOptions:

NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
self.rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"HelloReact" initialProperties:nil launchOptions:launchOptions];

viewDidAppear:中的ViewController.m

AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[self.view addSubview:delegate.rootView];

我对如何解决这个问题感到困惑。我已经尝试了以下所有方法:
  • npm start
  • npm start --reset-cache
  • 删除node_modules目录并重新安装
  • 卸载并重新安装node、watchman、react-native和npm
  • 在物理设备和模拟器上尝试
是否有人看到我的代码中有什么问题或者知道问题所在?我愿意通过电子邮件或电话进行交流以解决此问题。我现在很着急。
我同时遇到了其他问题。这里是我提出的另一个问题,其中可能包含一些信息:React Native: Unable to Resolve Module

1
你在浏览器中打开了开发服务器选项卡吗?它类似于 http://localhost:8081/debugger-ui - Andrew Li
https://facebook.github.io/react-native/docs/debugging.html - Andrew Li
我无法让摇晃功能正常工作并显示开发人员菜单。我正在物理设备上以调试模式运行。还需要做些什么才能让它出现? - tentmaking
仅在模拟器上运行时使用“localhost”才有效。对于在物理设备上运行,请使用主机机器的IP地址,这里是如何操作的。假设其他所有内容都类似于由react-native init生成的代码,则应该解决连接问题。 - NiFi
1
很棒,很高兴能帮忙! - NiFi
显示剩余3条评论
5个回答

5
在 iOS 设备上运行 React Native 应用程序需要指定主机的 IP 地址,而不是使用 localhost
jsCodeLocation = [NSURL URLWithString:@"http://DEV_SERVER_URI:8081/index.ios.bundle?platform=ios&dev=true"];

更具体的说明可以在这个答案中找到。


0

确保设备和Macbook连接到同一个WiFi网络,并使用闪电-USB电缆连接。 查看更多信息


0

这里还有一个可能的问题。你同时运行了expo和yarn,这会导致问题。因为expo和yarn共享同一个端口,所以也可能会出现问题。希望这能帮到你!


0
  1. 关闭自动打开的Metro Bundler窗口命令行。
  2. 再次运行命令,“react-native run-android”或“react-native run-ios”。

0

确保你的防火墙没有干扰你。我感到很愚蠢,因为我花了一个小时试图弄清楚为什么这不起作用,结果是我的防火墙在作怪 ‍♂️


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接