简体   繁体   English

在React.js和React Native应用程序之间重用代码

[英]Reuse code between React.js and React Native applications

I want to reuse some code that retrieves data from an API for two apps. 我想重用一些代码,从两个应用程序的API中检索数据。 One is an iOS app using React Native. 一个是使用React Native的iOS应用程序。 The other one is a website using React.js. 另一个是使用React.js的网站。

I initially coded the class that retrieves data from an API when I built the iOS app. 我最初编写了在构建iOS应用程序时从API检索数据的类。 Thus, I used the fetch method available in React Native. 因此,我使用了React Native中提供的fetch方法。

Unfortunately, there isn't such a method in React.js. 不幸的是,在React.js中没有这样的方法。 My best option if I want to reuse my code is to abstract the call of the React Native's fetch method by creating a class HTTPRequests with a method fetch which will call the React Native's fetch method or the '$.get' method depending on the lib used by the project: React.js or React Native. 如果我想重用我的代码,我最好的选择是通过使用方法fetch创建一个类HTTPRequests来抽象React Native的fetch方法的调用,该方法将调用React Native的fetch方法或'$ .get'方法,具体取决于lib项目使用:React.js或React Native。

My question is the following: How can I detect the using of React.js or React Native in my project. 我的问题如下:如何在项目中检测到React.js或React Native的使用。 My first idea is to detect if my JS code is executed through RCTRootView engine or a browser. 我的第一个想法是检测我的JS代码是通过RCTRootView引擎还是浏览器执行的。 But I've no idea how to accomplish this. 但我不知道如何做到这一点。

Any suggestion? 有什么建议吗?

Thanks! 谢谢!

My suggestion would be to move shared logic into separate module (bower, npm, ES6), generalize the way you request data through fetch polyfill, and never ever bother with detecting React/React.native in your project. 我的建议是将共享逻辑移动到单独的模块(bower,npm,ES6),概括通过fetch polyfill请求数据的方式,并且永远不会在项目中检测React / React.native。 JS code detection will make your code unnecessary complicated and hard to support when new versions of React/React.native will come up. 当新版本的React / React.native出现时,JS代码检测将使您的代码变得不必要复杂且难以支持。

I have successful experience of building a cross-platform application with React and React Native using the platform-specific extensions feature of React Native. 我使用React Native 的特定平台的扩展功能,使用React和React Native构建跨平台应用程序的成功经验。 I've just described how I structured the code in order to achieve that in a blog post Code sharing between React and React Native applications 我刚刚描述了如何构建代码以便在React和React Native应用程序之间的博客文章代码共享中实现这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM