mobx在react中应用

by Qaiser Abbas

由Qaiser Abbas

借助React Native Elements,Jest和MobX MST可以轻松实现现实世界中的ReactNative应用 (Real-world ReactNative apps made easy with React Native Elements, Jest, and MobX MST)

In this post, we’ll build a real-world mobile application in ReactNative. We’ll also explore some of the development practices and libraries, including the following:

在本文中,我们将在ReactNative中构建一个现实世界的移动应用程序。 我们还将探索一些开发实践和库,包括以下内容:

  • directory structure目录结构
  • state management (in Mobx)状态管理(在Mobx中)
  • code styling and linting tools (Prettier, ESLint, and Arirbnb style guide)

    代码的造型和掉毛工具( 更漂亮 , ESLint和Arirbnb风格指南 )

  • screen navigation using react-navigation

    使用React导航进行屏幕导航

  • user interface using React Native Elements

    使用React Native Elements的用户界面

  • and an important, but often ignored part: unit-testing your application (via Jest and Enzyme).

    还有一个重要但经常被忽略的部分:对应用程序进行单元测试(通过Jest和Enzyme )。

So let’s get started!

因此,让我们开始吧!

React中的状态管理 (State management in React)

React and ReactNative have made building Single Page Applications and Mobile Applications fun and easy, but they only cover the view of the applications. State Management and UI design can still be a painful part of building the app.

React和ReactNative使构建单页应用程序和移动应用程序变得轻松有趣,但是它们仅涵盖了应用程序的视图。 状态管理和UI设计仍然可能是构建应用程序的痛苦部分。

There are several popular State Management libraries available for React. I’ve used Redux, Mobx, and RxJS. While all three of them are good in their own ways, I’ve enjoyed MobX the most because of its simplicity, elegance, and powerful state management.

有几种流行的状态管理库可用于React。 我用过Redux,Mobx和RxJS。 他们三个人各有千秋,但MobX的简单性,优雅性和强大的状态管理使其成为我最喜欢的。

Redux, based primarily on the concepts of functional programming and pure functions, tries to solve the complexity of state management by imposing some restrictions on when updates are possible. These restrictions are reflected in three basic principles: a single source of truth, read-only state, and pure functions. You can read more about these principles in the Redux documentation.

Redux主要基于函数式编程和纯函数的概念,试图通过对何时可以更新施加一些限制来解决状态管理的复杂性。 这些限制反映在三个基本原则中:真相的单一来源,只读状态和纯函数。 您可以在Redux文档中阅读有关这些原则的更多信息。

While I’m a fan of functional programming, I’ve experienced that you have to deal with a lot of unnecessary boilerplate code when working with Redux. You also have to write code for dispatching actions and transforming state yourself.

虽然我是函数式编程的爱好者,但我已经体验到在使用Redux时必须处理很多不必要的样板代码。 您还必须编写代码来自己调度动作和转换状态。

Mobx, on the other hand, does this job for you, making it easier to maintain and more fun to work with. You need the right amount of code and restrictions in MobX to achieve superior state management and a good developer experience.

另一方面,Mobx会为您完成这项工作,从而使维护更轻松,并且使用起来更有趣。 您需要在MobX中使用适当数量的代码和限制,才能实现出色的状态管理和良好的开发人员体验。

In Redux, you also have to spend a substantial amount of time normalizing and de-normalizing your data. In MobX, you don’t need to normalize the data, and MobX automatically tracks the relations between state and derivations. We’ll go into this later.

在Redux中,您还必须花费大量时间对数据进行规范化和反规范化。 在MobX中,您无需对数据进行规范化,MobX会自动跟踪状态与派生之间的关系。 我们稍后再讨论。

RxJS is a reactive programming library for JavaScript. It is different from MobX in that RxJS allows you to react to events while in MobX. You observe the values (or state) and it helps you react to changes in state.

RxJS是JavaScript的React式编程库。 它与MobX的不同之处在于RxJS允许您在MobX中对事件做出React。 您观察值(或状态),并有助于您对状态变化做出React。

Although both RxJS and MobX provide the ability to perform reactive programming, they are quite different in their approaches.

尽管RxJS和MobX都提供执行React式编程的能力,但是它们的方法却大不相同。

关于我们的应用 (About our app)

The application we’ll be building is for a Book Store. It will mainly consist of two simple views: the Books View and the Authors View.

我们将构建的应用程序用于书店。 它主要包含两个简单的视图:“书籍”视图和“作者”视图。

The app will contain a navigation drawer with two menu options, allowing the user to switch between the two views. The first option will be for navigating to the Books View, and the other option will navigate to the Authors View.

该应用程序将包含一个带有两个菜单选项的导航抽屉,允许用户在两​​个视图之间切换。 第一个选项将导航到“书籍”视图,另一个选项将导航到“作者”视图。

The Books View will contain the list of books, as well as a tab allowing the user to switch between Fiction and Non-Fiction books. The Authors View will containing the list of authors.

图书视图将包含图书列表,以及允许用户在小说和非小说书籍之间切换的选项卡。 作者视图将包含作者列表。

We’ll be installing everything on a Mac OS. Most of the commands will be the same when you have Node installed, but if you face any issues, let me know, (or just google it).

我们将在Mac OS上安装所有内容。 当您安装Node时,大多数命令将是相同的,但是如果遇到任何问题,请告诉我(或只是用Google搜索)。

涵盖的主题 (Topics Covered)

We’ll cover different topics and the various libraries necessary to create and test a full blown React Native application:

我们将介绍不同的主题以及创建和测试完整的React Native应用程序所需的各种库:

  1. We’ll install create-react-native-app, and use it to bootstrap our Book Store application

    我们将安装create-react-native-app ,并使用它来引导我们的Book Store应用程序

  2. Setup Prettier, ESLint, and the Airbnb style guide for our project为我们的项目设置更漂亮,ESLint和Airbnb样式指南
  3. Add Drawer and Tabs Navigation using react-navigation使用react-navigation添加抽屉和标签导航
  4. Test our React components with Jest and Enzyme用Jest和Enzyme测试我们的React组件
  5. Manage the state of our app using MobX (mobx-state-tree). It will also involve some UI changes and more navigation. We’ll sort and filter the books by genre, and allow the user to see the Book detail screen when the user taps on a book.使用MobX(mobx-state-tree)管理应用程序的状态。 它还将涉及一些UI更改和更多导航。 我们将按流派对书籍进行排序和过滤,并允许用户在点击书籍时看到“书籍详细信息”屏幕。

Here’s a demo of the Bookstore app we’re going to build:

这是我们将要构建的Bookstore应用程序的演示:

我们不会涵盖的内容 (What we won’t cover)

There are a few things we won’t cover in this article, which you may want to consider in your project:

我们将在本文中介绍一些内容,您可能需要在项目中考虑这些内容:

  1. Tools for adding static type system in JavaScript, like flow and TypeScript

    用于在JavaScript中添加静态类型系统的工具,例如flow和TypeScript

  2. Although we will add some styling to our app, we won’t go into details concerning the different options available for adding styles in a ReactNative application. The styled-components library is one of the most popular for both React and ReactNative applications.

    尽管我们将在我们的应用程序中添加一些样式,但是我们不会详细介绍可用于在ReactNative应用程序中添加样式的不同选项。 样式化组件库是React和ReactNative应用程序中最受欢迎的组件之一。

  3. We won’t build a separate backend for our application. We will go through integration with the Google Books API, but we’ll use mock data for the most part.我们不会为我们的应用程序构建单独的后端。 我们将与Google Books API进行集成,但大部分将使用模拟数据。

使用create-react-native-app CLI(CRNA)创建React Native应用程序 (Create a React Native application using create-react-native-app CLI (CRNA))

Create React Native App is a tool created by Facebook and the Expo team that makes it a breeze to get started with a React Native project. We’ll initialize our ReactNative app using CRNA CLI. So let’s get started!

创建React Native应用程序是Facebook和Expo团队创建的工具,轻松启动React Native项目变得轻而易举。 我们将使用初始化我们ReactNative应用CRNA CLI。 因此,让我们开始吧!

Assuming that you have Node already installed, , we need to install create-react-native-app globally, so that we can initialize a new React Native project for our Book Store.

假设您已经安装了Node ,那么我们需要全局安装create-react-native-app ,以便我们可以为Book Store初始化一个新的React Native项目。

npm install -g create-react-native-app

Now, we can use the create-react-native-app CLI to create our new React Native project. Let’s name it bookstore-app:

现在,我们可以使用create-react-native-app CLI创建新的React Native项目。 让我们将其命名为bookstore-app

create-react-native-app bookstore-app

Once CRNA is done bootstrapping our React Native application, it will show some helpful commands. Let’s change the directory to the newly created CRNA app, and start it.

一旦完成CRNA引导我们的React Native应用程序的启动,它将显示一些有用的命令。 让我们将目录更改为新创建的CRNA应用程序,然后启动它。

cd bookstore-app npm start

This will start the packager, giving the option to launch the iOS or Android simulator, or open the app on a real device.

这将启动打包程序,并提供启动iOS或Android模拟器或在真实设备上打开应用程序的选项。

If you face any issues, please refer to either the React Native’s getting started guide or Create React Native app (CRNA) guide.

如果您遇到任何问题,请参考React Native的入门指南或Create React Native应用程序(CRNA)指南 。

通过Expo在真实设备上打开CRNA应用 (Opening the CRNA app on a real device via Expo)

When the app is started via npm start, a QR code will be displayed in your terminal. The easiest way to look at our bootstrapped app is using the Expo app. To do that:

通过npm start应用npm start ,QR码将显示在您的终端中。 查看我们的自举应用程序的最简单方法是使用Expo应用程序。 要做到这一点:

  1. Install the Expo client app on your iOS or Android device.

    在iOS或Android设备上安装Expo客户端应用。

  2. Make sure that you are connected to the same wireless network as your computer.确保您已将计算机连接到同一无线网络。
  3. Using the Expo app, scan the QR code from your terminal to open your project.使用Expo应用程序,从终端扫描QR码以打开您的项目。

在模拟器中打开CRNA应用 (Opening the CRNA app in a simulator)

To run the app on iOS Simulator, you’ll need to install Xcode. To run the app on an Android Virtual Device, you need to setup the Android development environment. Look at the react-native getting started guide for both the setups.

要在iOS Simulator上运行该应用,您需要安装Xcode。 要在Android虚拟设备上运行该应用,您需要设置Android开发环境。 请参阅这两种设置的本机入门指南。

设置更漂亮,ESLint和Airbnb样式指南 (Setup Prettier, ESLint, and an Airbnb style guide)

In this section, we’ll setup Prettier, ESLint, and Airbnb style guide to make sure our code not only looks pretty, but also runs code linting.

在本节中,我们将设置Prettier,ESLint和Airbnb样式指南,以确保我们的代码不仅看起来漂亮,而且还运行代码linting。

为什么要使用起绒工具? (Why use a linting tool?)

JavaScript is a dynamic language, and doesn’t have a static type system like languages such as C++ and Java. Because of this dynamic nature, JavaScript lacks the kind of tools available for static analysis that many other languages offer.

JavaScript是一种动态语言,没有像C ++和Java这样的静态类型系统。 由于这种动态特性,JavaScript缺乏许多其他语言提供的可用于静态分析的工具。

This results in hard-to-find bugs related to data types, and requires more effort in debugging and troubleshooting these issues, especially for inexperienced JavaScript developers.

这导致与数据类型相关的难以发现的错误,并且需要更多的精力来调试和解决这些问题,特别是对于没有经验JavaScript开发人员而言。

Since it’s not a compiled language, error are discovered when the JavaScript code is executed at runtime. There are tools like TypeScript and flow that help catch these kind of errors by adding a static type system to JavaScript, but we won’t be going into either of these tools in this tutorial.

由于它不是编译语言,因此在运行时执行JavaScript代码时会发现错误。 通过在JavaScript中添加静态类型系统,可以使用诸如TypeScript和Flow之类的工具来帮助捕获此类错误,但是在本教程中,我们不会涉及这两种工具。

On the other hand, there are linting tools like ESLint available that perform static analysis of the JavaScript code based on configurable rules. They highlight problems in the code that may be potential bugs, which helps developers discover problems in their code before it is executed.

另一方面,还有诸如ESLint之类的整理工具可以基于可配置的规则对JavaScript代码进行静态分析。 它们突出了代码中可能是潜在错误的问题,这有助于开发人员在代码执行之前发现问题。

安装和设置ESLint (Install and Setup ESLint)

A good linting tool is extremely important to ensure that quality is baked in from the beginning and errors are found early. ESLint also helps you implement style guidelines.

良好的起绒工具对于确保从一开始就引入质量并及早发现错误至关重要。 ESLint还可以帮助您实施样式准则。

To make sure we write high quality code and have the right tools from the very beginning of our Bookstore project, we’ll start our tutorial by first implementing linting tools. You can learn more about ESLint on their website.

为确保我们编写高质量的代码并从Bookstore项目的一开始就拥有正确的工具,我们将首先实施linting工具来开始本教程。 您可以在他们的网站上了解有关ESLint的更多信息。

ESLint is fully configurable and customizable. You can set your rules according to your preferences. However, different linting rules configurations have have been provided by the community. One of the popular ones is the Airbnb style guide, and this is the one we’ll use. This will include Airbnb’s ESLint rules, including ECMAScript 6+ and React.

ESLint是完全可配置和可定制的。 您可以根据自己的喜好设置规则。 但是,社区已提供了不同的掉毛规则配置。 最受欢迎的一种是Airbnb样式指南,这就是我们将要使用的指南。 这将包括Airbnb的ESLint规则,包括ECMAScript 6+和React。

First, we’ll install ESLint by running this command in the terminal:

首先,我们将在终端中运行以下命令来安装ESLint:

We’ll use Airbnb’s eslint-config-airbnb, which contains Airbnb’s ESLint rules, including ECMAScript 6+ and React. It requires specific versions of ESLint, eslint-plugin-import, eslint-plugin-react, and eslint-plugin-jsx-a11y. To list the peer dependencies and versions, run this command:

我们将使用Airbnb的eslint-config-airbnb ,其中包含Airbnb的ESLint规则,包括ECMAScript 6+和React。 它需要特定版本的ESLint,eslint-plugin-import,eslint-plugin-react和eslint-plugin-jsx-a11y。 要列出对等方依赖性和版本,请运行以下命令:

npm info "eslint-config-airbnb@latest" peerDependencies

At the time of this writing, these are the versions shown in the output from the above command:

在撰写本文时,这些是上述命令输出中显示的版本:

{ eslint: '^4.9.0',  'eslint-plugin-import': '^2.7.0',  'eslint-plugin-jsx-a11y': '^6.0.2',  'eslint-plugin-react': '^7.4.0' }

So let’s install these specific dependency versions by running this command:

因此,让我们通过运行以下命令来安装这些特定的依赖版本:

npm install -D eslint@^4.9.0 eslint-plugin-import@^2.7.0 eslint-plugin-jsx-a11y@^6.0.2 eslint-plugin-react@^7.4.0

This will install the necessary dependencies and generate the .eslintrc.js file in the project root directory. The .eslintrc.js file should have the following configurations:

这将安装必要的依赖项,并在项目根目录中生成.eslintrc.js文件。 .eslintrc.js文件应具有以下配置:

module.exports = {  "extends": "airbnb"};

代码样式 (Code styling)

While we have the linting covered with ESLint and the Airbnb style guide, a big part of code quality is consistent code styling. When you’re working on a team, you want to make sure that the code formatting and indentation is consistent throughout the team. Prettier is just the tool for that. It ensures that all the code conforms to a consistent style.

虽然我们在ESLint和Airbnb样式指南中介绍了棉绒,但是代码质量的很大一部分是一致的代码样式。 在团队中工作时,您要确保整个团队中的代码格式和缩进都是一致的。 漂亮只是工具。 它确保所有代码都符合一致的样式。

We’ll also add the ESLint plugin for Prettier, which will add Prettier as an ESLint rule and report differences as individual ESLint issues.

我们还将为Prettier添加ESLint插件 ,该插件会将Prettier添加为ESLint规则,并报告差异作为单个ESLint问题。

Now, there may be conflicts between the ESLint rules and the code formatting done by Prettier. Fortunately, there is a plugin available called eslint-config-prettier that turns off all rules that are unnecessary or might conflict with Prettier.

现在,ESLint规则与Prettier完成的代码格式之间可能存在冲突。 幸运的是,有一个名为eslint-config-prettier的插件可以关闭所有不必要的或可能与Prettier冲突的规则。

使用ESLint安装和设置更漂亮 (Install and Setup Prettier with ESLint)

Let’s install all the necessary packages, Prettier, and eslint-plugin-prettier. We’ll also need to install eslint-config-airbnb for this:

让我们安装所有必需的软件包,Prettier和eslint-plugin-prettier。 我们还需要为此安装eslint-config-airbnb:

npm install -D prettier prettier-eslint eslint-plugin-prettier eslint-config-prettier eslint-config-airbnb

NOTE: If ESLint is installed globally, then make sure eslint-plugin-prettier is also installed globally. A globally-installed ESLint cannot find a locally-installed plugin.

注意:如果ESLint是全局安装的,请确保eslint-plugin-prettier也已全局安装。 全局安装的ESLint无法找到本地安装的插件。

To enable eslint-plugin-prettier plugin, update your .eslintrc.js file to add the “prettier” plugin. And to show linting error on Prettier formatting rules, add the “rule” to show error on “prettier/prettier”. Here’s our updated .eslintrc.js:

要启用eslint-plugin-prettier插件,请更新您的.eslintrc.js文件以添加“ prettier”插件。 要显示漂亮的格式规则上的毛发错误,请添加“规则”以在“漂亮/漂亮”上显示错误。 这是我们更新的.eslintrc.js:

module.exports = {  "extends": [    "airbnb",    "prettier"  ],  rules: {    "prettier/prettier": "error",  },}

eslint-config-prettier also ships with a CLI tool to help you check if your configuration contains any rules that are unnecessary or conflict with Prettier. Let’s be proactive and do that.

eslint-config-prettier还附带一个CLI工具,可帮助您检查配置中是否包含不必要的规则或与Prettier冲突的规则。 让我们积极主动地做到这一点。

First, add a script for it to package.json:

首先,将脚本添加到package.json中:

{  "scripts": {    "eslint-check": "eslint --print-config .eslintrc.js | eslint-config-prettier-check"  }}

Now, run the “eslint-check” command to see ESLint and Prettier’s conflicting rules:

现在,运行“ eslint-check”命令以查看ESLint和Prettier的冲突规则:

npm run eslint-check

This will list the conflicting rules in the terminal. Let’s turn off the conflicting rules by updating the .eslintrc.js file. I also prefer singleQuote and trailingComma, so I’ll configure those rules as well. This is what our .eslintrc.js file looks like now:

这将在终端中列出冲突的规则。 让我们通过更新.eslintrc.js文件来关闭冲突规则。 我也更喜欢singleQuote和TrailingComma,因此我还将配置这些规则。 这是我们的.eslintrc.js文件现在的样子:

module.exports = {  "parser": "babel-eslint",  "extends": [    "airbnb",    "prettier"  ],  "plugins": [    "prettier"  ],  "rules": {    "prettier/prettier": "error",    "react/jsx-closing-bracket-location": "off",    "react/jsx-closing-tag-location": "off",    "react/jsx-curly-spacing": "off",    "react/jsx-equals-spacing": "off",    "react/jsx-first-prop-new-line": "off",    "react/jsx-indent": "off",    "react/jsx-indent-props": "off",    "react/jsx-max-props-per-line": "off",    "react/jsx-tag-spacing": "off",    "react/jsx-wrap-multilines": "off"  }}

If you now run eslint with the --fix flag, the code will be automatically formatted according to the Prettier styles.

如果现在使用--fix标志运行eslint ,则代码将根据Prettier样式自动设置格式。

配置VS Code以在保存时运行ESLint (Configure VS Code to run ESLint on save)

We can configure any IDE to automatically run ESLint on Save or as we type. Since we have also configured Prettier along with ESLint, our code will automatically be pretiffied. VS Code is an IDE popular in the JavaScript community, so I’ll show how to setup ESLint’s auto-fix on save using VS Code, but the steps would be similar in any IDE.

我们可以将任何IDE配置为在“保存”或键入时自动运行ESLint。 由于我们还与ESLint一起配置了Prettier,因此将自动美化我们的代码。 VS Code是JavaScript社区中流行的IDE,因此,我将向您展示如何使用VS Code在保存时设置ESLint的自动修复功能,但是步骤在任何IDE中都是相似的。

To configure VS Code to automatically run ESLint on Save, we first need to install the ESLint extension. Go to Extensions, search for the “ESLint” extension, and install it. Once the ESLint extension is installed, go to Preferences > User Settings, and set “eslint.autoFixOnSave” to true. Also make sure that “files.autoSave” is either set to “off”, “onFocusChange” or “onWindowChange”.

要将VS Code配置为在保存时自动运行ESLint,我们首先需要安装ESLint扩展。 转到扩展,搜索“ ESLint”扩展,然后安装它。 一旦安装了ESLint扩展,请转到Preferences > User Setti设置”,并将“ eslint.autoFixOnSave”设置为true。 还要确保将“ files.autoSave”设置为“ off”,“ onFocusChange”或“ onWindowChange”。

Now, open the file App.js. If the ESLint is configured correctly, you should see some linting error, like the “react/prefer-stateless-function”, “react/jsx-filename-extension”, and “no-use-before-define” errors. Let’s turn those “off” in the .eslintrc.js file. I also prefer singleQuote and trailingComma as I mentioned above, so I’ll configure those rules as well.

现在,打开文件App.js。 如果正确配置了ESLint,则应该看到一些掉毛错误,例如“ react / prefer-stateless-function”,“ react / jsx-filename-extension”和“ no-use-before-define”错误。 让我们在.eslintrc.js文件中将其“关闭”。 我也更喜欢如上所述的singleQuote和TrailingComma,因此我还将配置这些规则。

Here is the updated .eslintrc.js file.

这是更新的.eslintrc.js文件。

module.exports = {  "parser": "babel-eslint",  "extends": [    "airbnb",    "prettier"  ],  "plugins": [    "prettier"  ],  "rules": {    "prettier/prettier": [      "error",      {        "singleQuote": true,        "trailingComma": "all",      }    ],    "react/prefer-stateless-function": "off",    "react/jsx-filename-extension": "off",    "no-use-before-define": "off",    "react/jsx-closing-bracket-location": "off",    "react/jsx-curly-spacing": "off",    "react/jsx-equals-spacing": "off",    "react/jsx-first-prop-new-line": "off",    "react/jsx-indent": "off",    "react/jsx-indent-props": "off",    "react/jsx-max-props-per-line": "off",    "react/jsx-tag-spacing": "off",    "react/jsx-wrap-multilines": "off"  }}

I know this was a lot of work, considering that we haven’t even started working on our app yet! But trust me, this setup will be very beneficial for your projects in the long run, even if you’re a one person team. When you’re working with other developers, linting and programming standards will go a long way in reducing code defects and ensuring consistency in code style.

考虑到我们甚至还没有开始开发我们的应用程序,我知道这是很多工作! 但是请相信我,从长远来看,即使您是一个人的团队,这种设置对您的项目也将非常有益。 当您与其他开发人员一起工作时,整理和编程标准将在减少代码缺陷和确保代码样式的一致性方面大有帮助。

You can find the changes made in this section in this branch of the tutorial repository.

您可以在教程资料库的此分支中找到本节中所做的更改。

使用React导航的抽屉和标签导航 (Drawer and Tabs Navigation using react-navigation)

In this section, we’ll add the Drawer and Tabs Navigation using react-navigation.

在本节中,我们将使用react-navigation添加“抽屉和标签导航”。

Our Bookstore app will contain a navigation drawer with two menu options. The first menu item for the AuthorsScreen, containing the list of authors. The second menu item for the BooksScreen, containing the list of books.

我们的Bookstore应用程序将包含一个带有两个菜单选项的导航抽屉。 AuthorsScreen的第一个菜单项,包含作者列表。 BooksScreen的第二个菜单项,包含书单。

Tapping on a book will take the user to the BookDetail Screen. For navigation between the different views, we’ll use React Navigation to add navigation to our app. So let’s install it first:

轻按书籍会将用户带到“书籍详细信息”屏幕。 为了在不同视图之间导航,我们将使用React Navigation将导航添加到我们的应用程序。 因此,让我们先安装它:

npm install --save react-navigation

createStackNavigator (createStackNavigator)

Our ReactNative app will contain two modules:

我们的ReactNative应用程序将包含两个模块:

  • an Author module allowing the users to browse list of authors作者模块,允许用户浏览作者列表
  • a Books module, containing the list of books.书籍模块,其中包含书籍列表。

The Author and Book modules will be implemented using the StackNavigator from React Navigation. Think of StackNavigator as the history stack in a web browser. When the user clicks on a link, the URL is pushed to the browser history stack, and removed from the top of the history stack when the user presses the back button.

Author和Book模块将使用React Navigation中的StackNavigator实现。 将StackNavigator视为Web浏览器中的历史记录堆栈。 当用户单击链接时,URL被推送到浏览器历史记录堆栈,并在用户按下“后退”按钮时从历史记录堆栈的顶部删除。

export const BookStack = createStackNavigator({  Books: {    screen: BooksScreen,  },})
export const AuthorStack = createStackNavigator({  Authors: {    screen: AuthorsScreen,  },})

For BooksScreen and AuthorsScreen, we’ll simply add two stateless react components for now, with some buttons to test our screen navigation and drawer functionality:

对于BooksScreen和AuthorsScreen,我们现在仅添加两个无状态的react组件 ,并使用一些按钮来测试我们的屏幕导航和抽屉功能:

const BooksScreen = ({ navigation }) => (  <View>    <Button      onPress={() => navigation.navigate('Authors')}      title="Go to Authors"    />    <Button onPress={() => navigation.openDrawer()} title="Open Drawer" />  </View>)
const AuthorsScreen = ({ navigation }) => (  <Button    onPress={() => navigation.navigate('Books')}    title="Go back to Books"  />)

navigation.openDrawer() will trigger the drawer to open. navigation.navigate() allows the app to navigate to different screens.

navigation.openDrawer()将触发抽屉打开。 navigation.navigate()允许应用导航到不同的屏幕。

In our application, we’ll add a Drawer which will maintain the menu for our Author and Book modules. We’ll implement the drawer using React Navigation’s createDrawerNavigator.

在我们的应用程序中,我们将添加一个Drawer,它将维护Author和Book模块的菜单。 我们将使用React Navigation的createDrawerNavigator实现抽屉。

The first menu in the drawer will be for the Author module, and the second for the Book module. Author and Book Stack Navigators will both be inside the main DrawerStack.

抽屉中的第一个菜单用于“作者”模块,第二个菜单用于“书籍”模块。 作者和书籍堆栈导航器都将位于主DrawerStack内部。

Here’s the code for the drawer implementation:

这是抽屉实现的代码:

const App = createDrawerNavigator({  Books: {    screen: BookStack,  },  Authors: {    screen: AuthorStack,  },})

Here’s a diff of our latest changes.

这与我们的最新变化有所不同 。

In the file App.js, we’ve made the following changes:

在文件App.js中,我们进行了以下更改:

  1. We renamed the default export to App我们将默认导出重命名为App
  2. We added two stateless components for our screens, BooksScreen and AuthorsScreen.我们为屏幕添加了两个无状态组件,BooksScreen和AuthorsScreen。
  3. We added the StackNavigator from React Navigation to implement navigation for our app.

    我们从React Navigation中添加了StackNavigator,以实现我们应用程序的导航。

  4. We used createDrawerNavigator() from react-navigation to implement the Drawer Navigation. This renders the Drawer content, along with the menu options for Books and Authors.

    我们使用了react-navigation中的createDrawerNavigator()来实现Drawer Navigation。 这将呈现“抽屉”内容以及“书籍”和“作者”的菜单选项。

And after making the above changes, here’s what our UI looks like when we click on the “Open Drawer” button and navigate between screens.

进行了上述更改之后,这就是我们单击“打开抽屉”按钮并在屏幕之间导航时的UI外观。

目录结构 (Directory Structure)

It’s important to think about your application and how you’ll structure of your files and resources in the beginning of the project. While there are several ways you could structure your application code, I prefer co-locating files and tests using a feature-based architecture. Co-locating files related to a particular feature or module has a number of benefits.

重要的是要考虑您的应用程序以及在项目开始时如何构造文件和资源。 尽管可以通过多种方式来构造应用程序代码,但我更喜欢使用基于功能的体系结构来共同定位文件和测试。 与特定功能或模块相关的文件共定位有很多好处。

Let’s create an src directory where we’ll keep all our source files. Inside it, create two directories: one for the book view, named “book”, and the other for the author view, named “author”.

让我们创建一个src目录,我们将保留所有源文件。 在其中创建两个目录:一个目录用于书本视图,名为“ book”,另一个目录用于作者视图,名为“ author”。

Create index.js files within each of the two directories we just added. These files will export the components for each of our views. Move the code from App.js for the BookView and AuthorView components into these files, and import them instead.

在我们刚刚添加的两个目录中的每个目录中创建index.js文件。 这些文件将导出我们每个视图的组件。 将App.js中BookView和AuthorView组件的代码移到这些文件中,然后导入它们。

It’s important to note that refactoring should be a big part of the development workflow. We should continuously refactor our code to prepare ourselves for future changes and challenges. This has a big impact on productivity and change management in the long run.

值得注意的是,重构应该是开发工作流的重要组成部分。 我们应该不断重构代码,为将来的变化和挑战做好准备。 从长远来看,这对生产力和变更管理有很大影响。

Our app should still work as it was before the refactor. Here’s the file diff of our recent changes.

我们的应用程序应该仍然可以像重构前一样正常工作。 这是我们最近更改的文件差异 。

Each of the screens will have a title, which means that we’ll be duplicating the same code along with the styles. To keep our code DRY, let’s move the title to a separate file src/components/Title.js, and reuse it where needed. We’ll also move the main views into a new parent directory src/views to keep them separate from other components.

每个屏幕都有一个标题,这意味着我们将复制相同的代码以及样式。 为了使我们的代码保持干燥,让我们将标题移动到单独的文件src/components/Title.js ,并在需要的地方重复使用。 我们还将主视图移动到新的父目录src/views以使其与其他组件分离。

标签导航 (Tab Navigation)

The business requirement for our app is to have three tabs in the books view, to show all books by default, and additional tabs to show filtered books for the fiction and non-fiction books. Let’s use the createBottomTabNavigator from react-navigation to implement the Tab Navigation.

我们应用程序的业务需求是在书籍视图中具有三个选项卡,以默认显示所有书籍,并具有其他选项卡以显示小说和非小说类书籍的过滤书籍。 让我们使用react-navigation中的createBottomTabNavigator来实现选项卡导航。

import { createBottomTabNavigator } from 'react-navigation'
import { AllBooksTab, FictionBooksTab, NonfictionBooksTab } from ' components/book-type-tabs'
export default createBottomTabNavigator({  'All Books': AllBooksTab,  Fiction: FictionBooksTab,  Nonfiction: NonfictionBooksTab,})

We should also add a title on every screen to identify the currently selected screen. Let’s create a separate directory src/components for all the common components, and create a file for our Title component inside this new directory.

我们还应该在每个屏幕上添加一个标题,以标识当前选择的屏幕。 让我们为所有常见组件创建一个单独的目录src/components ,并在此新目录内为Title组件创建一个文件。

// src/components/Title.jsimport React from 'react'import { StyleSheet, Text } from 'react-native'
const styles = StyleSheet.create({  header: {    textAlign: 'center',    padding: 20,    marginTop: 20,    fontSize: 20,    color: '#fff',    backgroundColor: '#434343',  },})
export default ({ text }) => <Text style={styles.header}>{text}</Text>

Note that we’ve also added style to the <Text> component, importing both StyleSheet and Text from react-native.

请注意,我们还为<Te xt>组件添加了stylefrom react- native导入both Styl样式t an文本。

We’ll add the Title to each view component, providing the title text in the props. Also, since the Authors view just contains a list of authors, we don’t need a StackNavigator for it, so we’ll change it to a plain React component. Here’s what our src/views/author/index.js file looks like now:

我们将Title添加到每个视图组件,在道具中提供标题text 。 另外,由于Authors视图仅包含作者列表,因此我们不需要StackNavigator,因此将其更改为普通的React组件。 这是我们的src/views/author/index.js文件现在的样子:

// src/views/author/index.js
import Title from '../../components/Title'
export default ({ navigation }) => (  <View>    <Title text="Authors List" />    <Button onPress={() => navigation.openDrawer()} title="Open Drawer" />    <Button onPress={() => navigation.navigate('Books')} title="Go to Books" />  </View>)

Now, when we open the Books menu from the drawer, we’re able to switch tabs by clicking on the tabs at the bottom.

现在,当我们从抽屉中打开“书籍”菜单时,我们可以通过单击底部的标签来切换标签。

With those changes, we have our app’s navigations all done. Here’s the diff for our recent changes.

进行这些更改后,我们的应用程序导航全部完成。 这是我们最近变化的区别 。

React本机元素 (React Native Elements)

There are several UI component libraries for adding React Native components with style. Some of the more poular ones are React Native ElementsNativeBase, and Ignite. We’ll be using React Native Elements for our Bookstore app. So let’s first install react-native-elements:

有几个UI组件库可用于添加带样式的React Native组件。 一些更受欢迎的是React Native Elements NativeBase和Ignite 。 我们将在我们的Bookstore应用程序中使用React Native Elements。 因此,让我们首先安装react-native-elements:

npm install --save react-native-elements

使用react-native-elements创建我们的作者列表 (Creating our Authors List using react-native-elements)

Let’s use the ListItem component from React Native Elements to add a list of authors in our Author screen.

让我们使用React Native Elements中的ListItem组件在“作者”屏幕中添加作者列表。

For the Authors List, we’ll use the data and code from the ListItem demo. We’ll revisit ListItem into more detail when we implement the Book List screen.

对于作者列表,我们将使用ListItem演示中的数据和代码。 当我们实现Book List屏幕时,我们将更详细地介绍ListItem

Here’s the diff for our recent changes.

这是我们最近变化的区别 。

用Jest和Enzyme测试ReactNative组件 (Testing ReactNative components with Jest and Enzyme)

In this section, we’ll add some unit tests using Jest and Enzyme.

在本节中,我们将使用Jest和Enzyme添加一些单元测试。

开玩笑和酶设置 (Jest and Enzyme setup)

Having unit tests for your code is really important so that you can have confidence in your code when you want to change something. It really pays off when you’re adding more features, and you can make changes without the fear of breaking some existing functionality of your application as a result of the change. You know that your unit tests provide the safety net for your application from leaking out any defects into the production.

对代码进行单元测试非常重要,这样,当您要更改某些内容时,您可以对代码充满信心。 当您添加更多功能时,它确实会有所回报,并且您可以进行更改而不必担心更改会破坏应用程序的某些现有功能。 您知道单元测试可为您的应用程序提供安全网,以免将任何缺陷泄漏到生产中。

We’ll use Jest as our testing framework along with Airbnb’s JavaScript testing utility Enzyme. Enzyme has a flexible and intuitive interface that makes it very easy to assert, manipulate, and traverse React Components.

我们将把Jest与AirbnbJavaScript测试实用程序Enzyme一起用作我们的测试框架。 酶具有灵活直观的界面,使声明,操纵和遍历React组件变得非常容易。

The create-react-native-app kit already includes all the related Jest libraries and configurations. To work with Enzyme, we need to install enzyme and some related dependencies. Since we’re using React 16, we’ll be adding react-dom@16 and enzyme-adapter-react-16.

create-react-native-app工具包已经包含所有相关的Jest库和配置。 要使用酶,我们需要安装enzyme和一些相关的依赖项。 由于我们使用的是React 16,因此我们将添加react-dom@16enzyme-adapter-react-16

npm install -D enzyme react-dom@16 enzyme-adapter-react-16

We need to configure enzyme-adapter-react-16. We’ll do this during Jest setup. Create jestSetup.js file project’s root, with the following code:

我们需要配置enzyme-adapter-react-16 。 我们将在Jest设置过程中执行此操作。 使用以下代码创建jestSetup.js文件项目的根目录:

import { configure } from 'enzyme'import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })

Now, add this file to Jest’s configuration in package.json:

现在,将此文件添加到package.json Jest的配置中:

"jest": {    "preset": "jest-expo",    "setupTestFrameworkScriptFile": "<rootDir>/jestSetup.js"  },

标题组件的酶和快照测试 (Enzyme and snapshot tests for our Title component)

Now, we’re all set to add Enzyme tests. I prefer having tests co-located with my code. Let’s create a simple test for our Title component by adding a test file next to our Title component. In this test, we’ll simply shallow render the Title component, create a snapshot, and verify the component styles. Create the file src/components/__tests__/Title.js, with the following content:

现在,我们都准备添加酶测试。 我更喜欢将测试与我的代码放在一起。 通过在Title组件旁边添加一个测试文件,为Title组件创建一个简单的测试。 在此测试中,我们将仅浅化呈现Title组件,创建快照并验证组件样式。 创建文件src/components/__tests__/Title.js ,其内容如下:

import React from 'react'import { shallow } from 'enzyme'import Title from '../Title'
it('renders correctly', () => {  const wrapper = shallow(<Title text="Sample Text" />)  expect(wrapper).toMatchSnapshot()
expect(wrapper.prop('accessible')).toBe(true)  expect(wrapper.prop('style')).toEqual({    backgroundColor: '#434343',    color: '#fff',    fontSize: 20,    marginTop: 20,    padding: 20,    textAlign: 'center',  })})

Let’s run our our tests:

让我们运行我们的测试:

npm test

The tests should pass and generate a snapshot, giving the following output:

测试应该通过并生成快照,并提供以下输出:

In case you’re not familiar with Jest Snapshot testing, it is a great way to test React components or different kinds of outputs in general.

如果您对Jest Snapshot测试不熟悉,这是测试React组件或一般而言各种输出的一种好方法。

Basically, the toMatchSnapshot() call renders your component and creates a snapshot in the __snapshots__ directory (if the snapshot doesn’t already exist). After that, each time you re-run your tests, Jest will compare the output of the rendered component with that of the snapshot, and will fail if there is a mismatch. It will show the difference between the expected and the actual output. You can then review the differences, and if this difference is valid due to some change that you’ve implemented, you can re-run the tests with an -u flag, which signals Jest to update the snapshot with the new updates.

基本上, toMatchSnapshot()调用将呈现您的组件并在__snapshots__目录中创建快照(如果快照尚不存在)。 此后,每次重新运行测试时,Jest都会将渲染的组件的输出与快照的输出进行比较,如果不匹配,将失败。 它将显示预期输出与实际输出之间的差异。 然后,您可以查看差异,并且如果由于实施了某些更改而使差异有效,则可以使用-u标志重新运行测试,该标志指示Jest使用新更新来更新快照。

Here’s the diff for our changes so far for Jest and Enzyme test, including the generated snapshot.

这是到目前为止我们对Jest和Enzyme测试所做的更改 (包括生成的快照)的差异 。

酶转json序列化器 (enzyme-to-json serializer)

If you open up the snapshot file (src/components/__tests__/__snapshots__/Title.js.snap), you’ll notice that the content is not very readable. It is obfuscated by the code from the Enzyme wrappers, since we’re using Enzyme to render our component. Fortunately, there is the enzyme-to-json library available that converts the Enzyme wrappers to a format compatible with Jest snapshot testing.

如果打开快照文件( src/components/__tests__/__snapshots__/Title.js.snap ),您会注意到内容不是很可读。 由于我们正在使用酶来渲染我们的组件,因此它被酶包装器中的代码所混淆。 幸运的是,有可用的酶转json库,可将酶包装程序转换为与Jest快照测试兼容的格式。

Let’s install enzyme-to-json:

让我们安装酶转json:

npm install -D enzyme-to-json

And add it to Jest configurations as the snapshot serializer in pacakge.json:

并将其添加到Jest配置中,作为pacakge.json的快照序列化pacakge.json

"jest": {    ...    "snapshotSerializers": ["enzyme-to-json/serializer"]  },

Since we now expect the snapshot to be different from the previous snapshot, we’ll pass the -u flag to update the snapshot:

由于现在我们希望快照与之前的快照不同,因此我们将传递-u标志以更新快照:

npm test -- -u

If you open up the snapshot file again, you’ll see that the snapshot for the rendered Title component is correct.

如果再次打开快照文件,将会看到渲染的Title组件的快照是正确的。

We’ll dive more into Jest testing in the later sections.

在后面的部分中,我们将深入研究Jest测试。

使用React Navigation和Mobx Store管理状态 (Managing state with React Navigation and Mobx Store)

MobX或Redux用于状态管理 (MobX or Redux for state management)

While React is great for managing the view of your application, you generally need tools for store management of your application. I say generally, because you may not need a state management library at all — it all depends on the type of application you are building.

尽管React非常适合管理应用程序的视图,但是您通常需要工具来管理应用程序的商店。 我一般地说,因为您可能根本不需要状态管理库-这完全取决于您要构建的应用程序的类型。

There are several state management libraries out there, but the most popular are Redux and MobX. We’ll be using Mobx store for our Bookstore application.

这里有几个状态管理库,但是最受欢迎的是Redux和MobX。 我们将Mobx商店用于Bookstore应用程序。

I generally prefer MobX to Redux for store management, because I feel that it takes a lot more time to add new store data in Redux compared to MobX.

我通常更喜欢MobX而不是Redux来进行商店管理,因为与MobX相比,我认为在Redux中添加新的商店数据要花很多时间。

Some downsides to Redux:

Redux的一些缺点:

  • You need to add a lot of boilerplate code.您需要添加很多样板代码。
  • You have to write code for dispatching actions and transforming state yourself.您必须自己编写用于调度动作和转换状态的代码。
  • It forces you to implement things in a specific way. While this would be a good thing in some applications, I find that the amount of time it takes might not be worth it for many applications.它迫使您以特定方式实现事物。 尽管在某些应用程序中这是一件好事,但我发现对于许多应用程序而言,花费的时间可能并不值得。

Some advantages of MobX:

MobX的一些优点:

  • It adds that boilerplate for you, and does it well. I find it very easy to work with, whether it’s initial setup, or adding more functionality.它为您添加了样板,并且做得很好。 我发现使用它非常容易,无论是初始设置还是添加更多功能。
  • It doesn’t force you to implement your data flow in a specific way, and you have much more freedom. But again, that might be more problematic than helpful if you don’t setup your MobX stores correctly..它不会强迫您以特定的方式实现数据流,而且您拥有更大的自由度。 但是同样,如果您没有正确设置MobX存储,那可能比帮助还麻烦。

I know this is a sensitive topic, and I don’t want to start a debate here, so I’ll leave this topic for another day. But if you want more perspective on this, there are several perspectives on this debate around the internet. Redux and MobX are both great tools for store management.

我知道这是一个敏感的话题,所以我不想在这里开始辩论,所以我将把这个话题再留一天。 但是,如果您希望对此有更多的看法,那么围绕互联网的这场辩论有几种 看法 。 Redux和MobX都是用于商店管理的出色工具。

We’ll be gradually adding functionality to our store instead of adding it all at once, just to show you how easy it is to add more features to MobX stores.

我们将逐步向我们的商店中添加功能,而不是立即添加所有功能,只是向您展示向MobX商店中添加更多功能是多么容易。

MobX状态树 (MobX State Tree)

We won’t use Mobx directly, but a wrapper on MobX called mobx-state-tree. They’ve done a fine job of describing themselves, so I’ll just quote them here:

我们不会直接使用Mobx,而是使用MobX上的包装器mobx-state-tree 。 他们在描述自己方面做得很好,因此我在这里引用它们:

Simply put, mobx-state-tree tries to combine the best features of both immutability (transactionality, traceability and composition) and mutability (discoverability, co-location and encapsulation). — MST Github page

简而言之,mobx状态树试图结合不变性(事务性,可追踪性和组成)和可变性(可发现性,共置和封装)的最佳特征。 — MST Github页面

Let’s install mobx along with mobx-react and mobx-state-tree

让我们安装mobx以及mobx-react和mobx-state-tree

npm install --save mobx mobx-react mobx-state-tree

npm install --save mobx mobx-react mobx-state-tree

We’ll be using the Google Books API to fetch the books for our app. If you want to follow along, you’ll have to create a project in the Google Developers Console, enable Google Books API on it, and create an API Key in the project. Once you have the API Key, create a file keys.json in the project root, with the following content (replace YOUR_GOOGLE_BOOKS_API_KEY with your API key):

我们将使用Google Books API为我们的应用程序获取图书。 如果要继续学习,则必须在Google Developers Console中创建一个项目,在其上启用Google Books API,然后在该项目中创建一个API密钥。 获得API密钥后, keys.json在项目根目录中创建文件keys.json ,其中包含以下内容(将YOUR_GOOGLE_BOOKS_API_KEY替换为API密钥):

{  "GBOOKS_KEY": "YOUR_GOOGLE_BOOKS_API_KEY"}

NOTE: If you don’t want to go through this process of getting an API key, don’t worry. We won’t be using the Google API directly, and will mock the data instead.

注意 :如果您不想完成获取API密钥的过程,请不要担心。 我们不会直接使用Google API,而是会模拟数据。

Google Books API endpoint books/v1/volumes returns an array of items where each item contains information on a specific book. Here’s a cut down version of a book:

Google图书API终结点books/v1/volumes返回一系列items ,其中每个项目都包含特定图书的信息。 这是一本书的精简版:

{  kind: "books#volume",  id: "r_YQVeefU28C",  etag: "HeC4avg1XlM",  selfLink: "https://www.googleapis.com/books/v1/volumes/r_YQVeefU28C",  volumeInfo: {    title: "Breaking Everyday Addictions",    subtitle: "Finding Freedom from the Things That Trip Us Up",    authors: [      "David Hawkins"    ],    publisher: "Harvest House Publishers",    publishedDate: "2008-07-01",    description: "Addiction is a rapidly growing problem among Christians and non-Christians alike. Even socially acceptable behaviors, ...",    pageCount: 256,    printType: "BOOK",    categories: [      "Addicts"    ],    imageLinks: {      smallThumbnail: "http://books.google.com/books/content?id=r_YQVeefU28C",      thumbnail: "http://books.google.com/books/content?id=r_YQVeefU28C&printsec=frontcover"    },    language: "en",    previewLink: "http://books.google.com.au/books?id=r_YQVeefU28C&printsec=frontcover",    infoLink: "https://play.google.com/store/books/details?id=r_YQVeefU28C&source=gbs_api",    canonicalVolumeLink: "https://market.android.com/details?id=book-r_YQVeefU28C"  }}

We won’t be using all the fields returned in the API response. So we’ll create our MST model for only the data we need in our ReactNative app. Let’s define our Book model in MST.

我们不会使用API​​响应中返回的所有字段。 因此,我们将只为ReactNative应用程序中所需的数据创建MST模型。 让我们在MST中定义Book模型。

Create a new directory structure stores/book inside src, and create a new file index.js inside it:

src内创建一个新的目录结构stores/book ,并在其中创建一个新文件index.js

// src/stores/book/index.jsimport { types as t } from 'mobx-state-tree'
const Book = t.model('Book', {  id: t.identifier(),  title: t.string,  pageCount: t.number,  authors: t.array(t.string),  image: t.string,  genre: t.maybe(t.string),  inStock: t.optional(t.boolean, true),})

In the above MST node definition, our Book model type is defining the shape of our node — of type Book — in the in the MobX State Tree. The types.modeltype in MST is used to describe the shape of an object. Giving the model a name isn’t required, but is recommended for debugging purpose.

在上面的MST节点定义,我们的Book模型类型定义了节点的形状-类型的Book -在中MobX国树。 MST中的types.model类型用于描述对象的形状。 不需要给模型起一个名字,但是推荐给模型起调试的作用。

The second argument, the properties argument, is a key-value pair, where the key is the name of a property, and the value is its type. In our model, id is the identifier, title is of type string, pageCount is of type number, authors is an array of strings, genre is of type string, inStock of type boolean, and image of type string.

第二个参数,即属性参数,是一个键值对,其中键是属性的名称,值是属性的类型。 在我们的模型中, id标识符title字符串类型, pageCount数字类型, authors字符串数组genre字符串类型, inStockboolean类型, imagestring类型。

All the data is required by default to create a valid node in the tree, so if we tried to insert a node without a title, MST won’t allow it, and will throw an error.

默认情况下,所有数据都是在树中创建有效节点所必需的,因此,如果我们尝试插入不带标题的节点,MST将不允许它,并且会引发错误。

The genre will be mapped to the categories field (first index value of the categories array) of the Google Books API data. It may or may not be there in the response. Therefore, we’ve made it of type maybe. If the data for genre is not there in the response, genre will be set to null in MST, but if it’s there, it must be of type string for it to be valid.

genre将映射到Google Books API数据的categories字段(类别数组的第一个索引值)。 响应中可能有也可能没有。 因此,我们将其设置为maybe 。 如果响应中不存在流派的数据,则在MST中genre将被设置为null ,但是如果存在,则genre的类型必须为string类型才有效。

Since inStock is our own field, and is not returned in the response from the Google Books API, we’ve made it optional and have given it a default value of true. We could have simply assigned it the value true, since for primitive types MST can infer type from the default value. So inStock: true is the same as inStock: t.optional(t.boolean, true).

由于inStock是我们自己的字段,并且不会从Google Books API的响应中返回,因此我们将其设为可选,并将其默认值设置为true。 我们可以简单地为其指定值true ,因为对于基本类型,MST可以从默认值推断类型。 因此, inStock: trueinStock: t.optional(t.boolean, true)

The creating models section of the mobx-state-tree documentation goes into detail about creating models in MST.

mobx-状态树文档的“ 创建模型”部分详细介绍了如何在MST中创建模型。

// src/stores/book/index.jsconst BookStore = t  .model('BookStore', {    books: t.array(Book),  })  .actions(self => {    function updateBooks(books) {      books.forEach(book => {        self.books.push({          id: book.id,          title: book.volumeInfo.title,          authors: book.volumeInfo.authors,          publisher: book.volumeInfo.publisher,          image: book.volumeInfo.imageLinks.smallThumbnail,        })      })    }
const loadBooks = process(function* loadBooks() {      try {        const books = yield api.fetchBooks()        updateBooks(books)      } catch (err) {        console.error('Failed to load books ', err)      }    })
return {      loadBooks,    }  })

MST trees are protected by default. This means that only the MST actions can change the state of the tree.

MST树默认情况下受保护。 这意味着只有MST动作才能更改树的状态。

We’ve defined two actions: updateBooks is a function that is only called by the loadBooks function, so we’re not exposing it to the outside world. loadBooks on the other hand, is exposed (we’re returning it), and can be called from outside the BookStore.

我们已经定义了两个动作: updateBooks是一家仅由调用函数loadBooks功能,所以我们不会将其暴露于外界。 另一方面, loadBooks是公开的(我们要返回它),可以从BookStore外部进行调用。

Asynchronous actions in MST are written using generators, and always return a promise. In our case, loadBooks needs to be asynchronous, since we’re making an Ajax call to the Google Books API.

MST中的异步操作是使用生成器编写的,并且始终返回promise。 在本例中,由于我们正在对Google Books API进行Ajax调用,因此loadBooks必须是异步的。

We’ll maintain a single instance of the BookStore. If the store already exists, we’ll return the existing store. If not, we’ll create one and return that new store:

我们将维护BookStore的单个实例。 如果商店已经存在,我们将退回现有商店。 如果没有,我们将创建一个并返回该新商店:

// src/stores/book/index.jslet store = null
export default () => {  if (store) return store
store = BookStore.create({ books: {} })  return store}

在我们看来使用MST商店 (Using the MST store in our view)

Let’s start with the All Books view. To do that, we’ll create a new file containing our BookListView component:

让我们从“所有书籍”视图开始。 为此,我们将创建一个包含BookListView组件的新文件:

import React, { Component } from 'react'import { observer } from 'mobx-react'import BookStore from '../../../stores/book'import BookList from './BookList'
@observerclass BookListView extends Component {  async componentWillMount() {    this.store = BookStore()    await this.store.loadBooks()  }
render() {    return <BookList books={this.store.books} />  }}

As you can see, we’re initializing the BookStore in componentWillMount, and then calling loadBooks() to fetch the books from the Google Books API asynchronously. The BookList component iterates over the books array inside the BookStore, and renders the Book component for each book. Now, we just need to add this BookListView component to AllBooksTab.

如您所见,我们正在componentWillMount初始化BookStore ,然后调用loadBooks()以异步地从Google Books API中获取书籍。 BookList组件迭代BookStore内的books数组,并为每本书呈现Book组件。 现在,我们只需要将此BookListView组件添加到AllBooksTab

If you start the app now, you’ll see that the books are loading as expected.

如果立即启动应用程序,您会看到书籍正在按预期加载。

Note that I’m using Pascal case naming convention for a file that returns a single React component as the default export. For everything else, I use Kebab case. You may decide to choose a different naming convention for your project.

请注意,我对返回单个React组件作为默认导出的文件使用Pascal大小写命名约定。 对于其他一切,我都使用烤肉串盒。 您可以决定为项目选择其他命名约定。

If you run npm start now, you should see a list of books fetched by the Google API.

如果您现在运行npm start ,应该会看到Google API提取的书籍列表。

Here’s the diff for our changes so far.

到目前为止,这是我们所做更改的区别 。

为我们的MST BookStore添加测试 (Adding tests for our MST BookStore)

Let’s add some unit tests for our BookStore. However, our store is talking to our API, which calls the Google API. We can add integration tests for our store, but to add unit tests, we need to mock the API somehow.

让我们为BookStore添加一些单元测试。 但是,我们的商店正在与我们的API(称为Google API)进行通信。 我们可以为商店添加集成测试,但是要添加单元测试,我们需要以某种方式模拟API。

A simple way to mock the API is to use Jest Manual Mocks by creating the __mocks__ directory next to our existing api.js file. Inside it, create another api.js, the mocked version of our API fetch calls. Then, we just call jest.mock('../api')in our test to use this mocked version.

模拟API的一种简单方法是通过在现有api.js文件旁边创建__mocks__目录来使用Jest Manual api.js 。 在其中创建另一个api.js ,这是我们API调用的api.js版本。 然后,我们只需在测试中调用jest.mock('../api')即可使用此模拟版本。

MobX状态树中的依赖注入 (Dependency Injection in MobX State Tree)

We won’t be using Jest Manual Mocks. I’d like to show you another feature in MST, and demonstrate how easy it is to mock our API using MST. We’ll use Dependency injection in MobX State Tree to provide an easy way to mock the API calls, making our store easy to test. Note that our MST store can also be tested without Dependency Injection using Jest Mocks, but we’re doing it this way just for demonstration.

我们不会使用Jest Manual Mocks。 我想向您展示MST的另一个功能,并演示使用MST模拟我们的API有多么容易。 我们将在MobX状态树中使用依赖注入,以提供一种简单的方法来模拟API调用,从而使我们的商店易于测试。 请注意,我们的MST存储库也可以在不使用Jest Mocks进行依赖注入的情况下进行测试,但是我们这样做只是为了演示。

It is possible to inject environment-specific data to a state tree by passing an object as the second argument to the BookStore.create() call. This object will be accessible by any model in the tree by calling getEnv(). We’ll be injecting a mock API in our BookStore, so let’s first add the optional api parameter to the default export, and set it to the actual bookApi by default.

通过将对象作为第二个参数传递给BookStore.create()调用,可以将特定于环境的数据注入状态树。 树中的任何模型都可以通过调用getEnv()来访问此对象。 我们将在我们的BookStore中注入一个模拟API,因此我们首先将可选的api参数添加到默认导出中,并将其默认设置为实际的bookApi

// src/stores/book/index.jslet store = null
export default () => {  if (store) return store
store = BookStore.create({ books: {} })  return store}

Now, add an MST View for the injected API by grabbing it using getEnv(). Then use it in the loadBooks function as self.api.fetchBooks():

现在,使用getEnv()抓住注入的API添加一个MST视图 。 然后用它在loadBooks充当self.api.fetchBooks()

// src/stores/book/index.js// ....views(self => ({    get api() {      return getEnv(self).api    },}))

Let’s now create a mock API with the same fetch function as the real API fetch function:

现在让我们创建一个模拟API,其提取功能与真实的API提取功能相同:

// src/stores/book/mock-api/api.jsconst books = require('./books')
const delayedPromise = (data, delaySecs = 2) =>  new Promise(resolve => setTimeout(() => resolve(data), delaySecs * 1000))
const fetchBooks = () => delayedPromise(books)
export default {  fetchBooks,}

I’ve added a delay in response so that the response is not sent immediately. I’ve also created a JSON file with the some data similar to that of the response sent by the Google Books API src/stores/book/mock-api/books.json.

我添加了一个延迟响应,以便不会立即发送响应。 我还创建了一个JSON文件,其中的一些数据类似于Google Books API src/stores/book/mock-api/books.json发送的响应。

Now, we’re ready to inject the mock API into our tests. Create a new test file for our store with the following content:

现在,我们准备将模拟API注入我们的测试中。 使用以下内容为我们的商店创建一个新的测试文件:

// src/stores/book/__tests__/index.jsimport { BookStore } from '../index'import api from '../mock-api/api'
it('bookstore fetches data', async () => {  const store = BookStore.create({ books: [] }, { api })  await store.loadBooks()  expect(store.books.length).toBe(10)})

Run the store test:

运行商店测试:

npm test src/stores/book/__tests__/index.js

You should see the test pass.

您应该看到测试通过。

添加图书过滤器并应用TDD (Adding the books filter and applying TDD)

I believe in a hybrid approach to Test Driven Development. In my experience, it works best if you add some basic functionality first when starting a project, or when you’re adding a new module or a major functionality from scratch. Once the basic setup and structure is implemented, then TDD works really well.

我相信采用混合方法进行测试驱动开发。 以我的经验,最好在启动项目时或在从头开始添加新模块或主要功能时先添加一些基本功能。 一旦实现了基本的设置和结构,TDD就可以很好地工作。

But I do believe that TDD is the best way to approach a problem space in code. It not only forces you to have better code quality and design, but also ensures that you have atomic unit tests. Additionally it makes sure your unit tests are more focused on testing specific functionality, rather than stuffing too many assertions in a test.

但是我确实相信TDD是解决代码中问题空间的最佳方法。 它不仅迫使您具有更好的代码质量和设计,而且还确保您具有原子单元测试。 另外,它确保您的单元测试更加专注于测试特定功能,而不是在测试中填充过多的断言。

Before we start adding our tests and making changes to our store, I’ll change the delay in our mock API to 300 millisecs to ensure that our tests run faster.

Before we start adding our tests and making changes to our store, I'll change the delay in our mock API to 300 millisecs to ensure that our tests run faster.

const fetchBooks = () => delayedPromise(books, 0.3)

We want a filter field in our BookStore model, and a setGenre() action in our store for changing the value of the this filter.

We want a filter field in our BookStore model, and a setGenre() action in our store for changing the value of the this filter .

it(`filter is set when setGenre() is called with a valid filter value`, async () => {  store.setGenre('Nonfiction')  expect(store.filter).toBe('Nonfiction')})

We want to run tests only for our BookStore, and keep the tests running and watching for changes. They will re-run when the code has been changed. So we’ll use the watch command and use file path pattern matching:

We want to run tests only for our BookStore, and keep the tests running and watching for changes. They will re-run when the code has been changed. So we'll use the watch command and use file path pattern matching:

npm test stores/book -- --watch

The above test should fail, because we haven’t written the code yet to make the test pass. The way that TDD works is that you write an atomic test to test the smallest unit of a business requirement. Then you add code to make just that test pass. You go through the same process iteratively, until you’ve added all the business requirements. To make our test pass, we’ll have to add a filterfield of ENUM type in our BookStore model:

The above test should fail, because we haven't written the code yet to make the test pass. The way that TDD works is that you write an atomic test to test the smallest unit of a business requirement. Then you add code to make just that test pass. You go through the same process iteratively, until you've added all the business requirements. To make our test pass, we'll have to add a filter field of ENUM type in our BookStore model:

.model('BookStore', {    books: t.array(Book),    filter: t.optional(        t.enumeration('FilterEnum', ['All', 'Fiction', 'Nonfiction']),        'All'    ),})

And add an MST action which will allow us to change the filter value:

And add an MST action which will allow us to change the filter value:

const setGenre = genre => {  self.filter = genre}
return {  //...  setGenre,}

With these two changes, we should be in the green. Let’s also add a negative test for an invalid filter value:

With these two changes, we should be in the green. Let's also add a negative test for an invalid filter value:

it(`filter is NOT set when setGenre() is called with an invalid filter value`, async () => {  expect(() => store.setGenre('Adventure')).toThrow()})

And this test should also pass. This is because we’re using an ENUM type in our MST store, and the only allowed values are All, Fiction, and Nonfiction.

And this test should also pass. This is because we're using an ENUM type in our MST store, and the only allowed values are All , Fiction , and Nonfiction .

Here’s the diff of our recent changes.

Here's the diff of our recent changes .

Sorting and filtering the books (Sorting and filtering the books)

The first index value in the categories field of the mock data categorizes the book as Fiction or Nonfiction. We will use it to filter the books for our Fiction and Nonfiction tabs, respectively.

The first index value in the categories field of the mock data categorizes the book as Fiction or Nonfiction . We will use it to filter the books for our Fiction and Nonfiction tabs, respectively.

We also want our books to always be sorted by title. Let’s add a test for this:

We also want our books to always be sorted by title. Let's add a test for this:

Let’s first add a test for sorting the books:

Let's first add a test for sorting the books:

it(`Books are sorted by title`, async () => {  const books = store.sortedBooks  expect(books[0].title).toBe('By The Book')  expect(books[1].title).toBe('Jane Eyre')})

To make our test pass, we’ll add a view named sortedBooks in our BookStoremodel:

To make our test pass, we'll add a view named sortedBooks in our BookStore model:

get sortedBooks() {  return self.books.sort(sortFn)},

And with this change, we should be in the green again.

And with this change, we should be in the green again.

About MST Views (About MST Views)

We just added the sortedBooks view in our BookStore model. To understand how MST Views work, we’ll have to understand MobX. The key concept behind MobX is: anything that can be derived from the application state should be derived, automatically.

We just added the sortedBooks view in our BookStore model. To understand how MST Views work, we'll have to understand MobX. The key concept behind MobX is: anything that can be derived from the application state should be derived, automatically.

In this egghead.io video, the MobX creator Michel Weststrate explains the key concepts behind MobX. I’ll quote a key concept here:

In this egghead.io video , the MobX creator Michel Weststrate explains the key concepts behind MobX. I'll quote a key concept here:

MobX is built around four core concepts. Actions, observable state, computed values, and reactions… Find the smallest amount of state you need, and derive all the other things… — Michel Weststrate

MobX is built around four core concepts. Actions, observable state, computed values, and reactions… Find the smallest amount of state you need, and derive all the other things… — Michel Weststrate

The computed values should be pure functions, and in terms of depending only on observable values or other computed values they should have no side effects. Computed properties are lazily evaluated, and their value is evaluated only when their value is requested. The computed values are also cached in MobX, and this cached value is returned when this computed property is accessed. When there’s a change in any of the observable values being used in it, the Computed property is recomputed.

The computed values should be pure functions, and in terms of depending only on observable values or other computed values they should have no side effects. Computed properties are lazily evaluated, and their value is evaluated only when their value is requested. The computed values are also cached in MobX, and this cached value is returned when this computed property is accessed. When there's a change in any of the observable values being used in it, the Computed property is recomputed.

MST Views are derived from the current observable state. Views can be with or without arguments. Views without arguments are basically Computed values from MobX, defined using getter functions. When an observable value is changed from an MST action, the affected view gets recomputed, triggering a change (reaction) in the @observer components.

MST Views are derived from the current observable state. Views can be with or without arguments. Views without arguments are basically Computed values from MobX, defined using getter functions. When an observable value is changed from an MST action, the affected view gets recomputed, triggering a change (reaction) in the @observer components.

Adding tests for genre filter (Adding tests for genre filter)

We know that there are seven Nonfiction books in the mock data. Let’s now add a test for filtering by genre:

We know that there are seven Nonfiction books in the mock data. Let's now add a test for filtering by genre :

it(`Books are sorted by title`, async () => {  store.setGenre('Nonfiction')  const books = store.sortedBooks  expect(books.length).toBe(7)})

To make filtering by genre work, we’ll add a genre field of string type in our Book model, and map it to the volumeInfo.categories[0] received from the API response. We’ll also change the sortedBooks view getter in our BookStoremodel to filter the books before sorting them:

To make filtering by genre work, we'll add a genre field of string type in our Book model, and map it to the volumeInfo.categories[0] received from the API response. We'll also change the sortedBooks view getter in our BookStore model to filter the books before sorting them:

get sortedBooks() {  return self.filter === 'All'    ? self.books.sort(sortFn)    : self.books.filter(bk => bk.genre === self.filter).sort(sortFn)},

And again, all tests are passing.

And again, all tests are passing.

Here’s the diff of our recent changes.

Here's the diff of our recent changes .

Update the UI on tab change (Update the UI on tab change)

NOTE: From here on, we’ll use the mock data for our actual API calls instead of making Ajax requests to Google Books API. To do this, I’ve changed the bookApi in the stores/book/index.js to point to the mock API (./mock-api/api.js).

NOTE : From here on, we'll use the mock data for our actual API calls instead of making Ajax requests to Google Books API. To do this, I've changed the bookApi in the stores/book/index.js to point to the mock API ( ./mock-api/api.js ).

Note also that the display for all three tabs (“All”, “Fiction” and “NonFiction”) is similar. The layout and format of the items would be the same, but the only difference is the data that they’ll display. And since MobX allows us to keep our data completely separate from the view, we can get rid of the three separate views, and use the same component for all the three tabs.

Note also that the display for all three tabs (“All”, “Fiction” and “NonFiction”) is similar. The layout and format of the items would be the same, but the only difference is the data that they'll display. And since MobX allows us to keep our data completely separate from the view, we can get rid of the three separate views, and use the same component for all the three tabs.

This means that we don’t need the three separate tabs anymore. So we’ll delete the book-type-tabs.js file, and use the BookListView component directly in our TabNavigator for all three tabs. We’ll use the tabBarOnPress callback to trigger the call to setGenre() in our BookStore. The routeName, available on the navigation state object, is passed in to setGenre() to update the filter when user presses a tab.

This means that we don't need the three separate tabs anymore. So we'll delete the book-type-tabs.js file, and use the BookListView component directly in our TabNavigator for all three tabs. We'll use the tabBarOnPress callback to trigger the call to setGenre() in our BookStore . The routeName , available on the navigation state object, is passed in to setGenre() to update the filter when user presses a tab.

Here’s the updated TabNavigator:

Here's the updated TabNavigator:

// src/views/book/index.js
export default observer(  createBottomTabNavigator(    {      All: BookListView,      Fiction: BookListView,      Nonfiction: BookListView,    },    {      navigationOptions: ({ navigation }) => ({        tabBarOnPress: () => {          const { routeName } = navigation.state          const store = BkStore()          store.setGenre(routeName)        },      }),    }  ))

Note that we’re wrapping createBottomTabNavigator in MobX observer. This is what converts a React component class or stand-alone render function into a reactive component. In our case, we want the filter in our BookStore to change when tabBarOnPress is called.

Note that we're wrapping createBottomTabNavigator in MobX observer . This is what converts a React component class or stand-alone render function into a reactive component. In our case, we want the filter in our BookStore to change when tabBarOnPress is called.

We’ll also change the view to get sortedBooks instead of books.

We'll also change the view to get sortedBooks instead of books.

// src/views/book/components/BookListView.js
class BookListView extends Component {  async componentWillMount() {    this.store = BkStore()    await this.store.loadBooks()  }
render() {    const { routeName } = this.props.navigation.state    return (      <View>        <Title text={`${routeName} Books`} />        <BookList books={this.store.sortedBooks} />      &lt;/View>    )  }}

Styling our Book list (Styling our Book list)

Our Book list just lists the name and author of each book, but we haven’t added any styling to it yet. Let’s do that using the ListItem component from react-native-elements. This is a simple change:

Our Book list just lists the name and author of each book, but we haven't added any styling to it yet. Let's do that using the ListItem component from react-native-elements . This is a simple change:

// src/views/book/components/Book.js
import { ListItem } from 'react-native-elements'
export default observer(({ book }) => (  <ListItem    avatar={{ uri: book.image }}    title={book.title}    subtitle={`by ${book.authors.join(', ')}`}  />))

And here’s what our view looks like now:

And here's what our view looks like now:

![BookList with react-native-elements.png](./BookList with react-native-elements.png)

![BookList with react-native-elements.png](./BookList with react-native-elements.png)

Here’s the diff of our recent changes.

Here's the diff of our recent changes .

Add Book details (Add Book details)

We’ll add a field selectedBook to our BookStore which will point to the selected Book model.

We'll add a field selectedBook to our BookStore which will point to the selected Book model.

selectedBook: t.maybe(t.reference(Book))

We’re using a MST reference for our selectedBook observable. References in MST stores make it easy to make references to data and interact with it, while keeping the data normalized in the background.

We're using a MST reference for our selectedBook observable. References in MST stores make it easy to make references to data and interact with it, while keeping the data normalized in the background.

We’ll also add an action to change this reference:

We'll also add an action to change this reference:

const selectBook = book => {  self.selectedBook = book}

When a user taps on a book in the BookListView, we want to navigate the user to the BookDetail screen. So we’ll create a showBookDetail function for this, and pass it as a prop to the child components:

When a user taps on a book in the BookListView , we want to navigate the user to the BookDetail screen. So we'll create a showBookDetail function for this, and pass it as a prop to the child components:

// src/views/book/components/BookListView.jsconst showBookDetail = book => {  this.store.selectBook(book)  this.props.navigation.navigate('BookDetail')}

In the Book component, we call the above showBookDetail function on onPressevent on the Book ListItem:

In the Book component, we call the above showBookDetail function on onPress event on the Book ListItem :

// src/views/book/components/Book.js
onPress={() => showBookDetail(book)}

Let’s now create the BookDetailView that will be displayed when a user presses a book:

Let's now create the BookDetailView that will be displayed when a user presses a book:

// src/views/book/components/BookDetailView.js
export default observer(() => {  const store = BkStore()  const book = store.selectedBook
return (    <View>      <View>        <Card title={book.title}>          <View>            <Image              resizeMode="cover"              style={{ width: '60%', height: 300 }}              source={{ uri: book.image }}            />            <Text>Title: {book.title}</Text>            <Text>Genre: {book.genre}</Text>            <Text>No of pages: {book.pageCount}</Text>            <Text>Authors: {book.authors.join(', ')}</Text>            <Text>Published by: {book.publisher}</Text>          </View>        </Card>      </View>    </View>  )})

Previously we only had tabs, but now we want to show the detail when the user taps on a book. So we’ll export a createStackNavigator instead of exporting createBottomTabNavigator directly. The createStackNavigator will have two screens on the stack, the BookList and the BookDetail screen:

Previously we only had tabs, but now we want to show the detail when the user taps on a book. So we'll export a createStackNavigator instead of exporting createBottomTabNavigator directly. The createStackNavigator will have two screens on the stack, the BookList and the BookDetail screen:

// src/views/book/index.jsexport default createStackNavigator({  BookList: BookListTabs,  BookDetail: BookDetailView,})

Note that we’re having the List view and the Detail view inside the createStackNavigator. This is because we want to share the the same BookDetailView only with different content (filtered books). If we wanted a different detail view to show up from different tabs, then we would have created two separate StackNavigators, and included them inside a TabNavigator. Something like this:

Note that we're having the List view and the Detail view inside the createStackNavigator . This is because we want to share the the same BookDetailView only with different content (filtered books). If we wanted a different detail view to show up from different tabs, then we would have created two separate StackNavigators, and included them inside a TabNavigator. 像这样:

const TabStackA = createStackNavigator({  Main: MainScreen,  Detail: DetailScreen,});
const TabStackB = createStackNavigator({  Main: MainScreen,  Detail: DetailScreen,});
export default createBottomTabNavigator(  {    TabA: TabStackA,    TabB: TabStackB,  })

Here’s the diff of our recent changes.

Here's the diff of our recent changes .

Styling the tabs (Styling the tabs)

Our tab labels look a bit small, and are hitting the bottom of the screen. Let’s fix that by increasing the fontSize and adding some padding:

Our tab labels look a bit small, and are hitting the bottom of the screen. Let's fix that by increasing the fontSize and adding some padding :

// src/views/book/index.js
const BookListTabs = observer(  createBottomTabNavigator(    {      All: BookListView,      Fiction: BookListView,      Nonfiction: BookListView,    },    {      navigationOptions: ({ navigation }) => ({        // ...      }),      tabBarOptions: {        labelStyle: {          fontSize: 16,          padding: 10,        },      },    }  ))

Let’s run our app, tap on a book, and the Book detail screen should be displayed with the book details. Here’s the repo of our finished app.

Let's run our app, tap on a book, and the Book detail screen should be displayed with the book details. Here's the repo of our finished app.

感谢您的阅读! (Thank you for reading!)

And that concludes our tutorial on creating a ReactNative application with MobX store. I hope you enjoyed the post and found it useful.

And that concludes our tutorial on creating a ReactNative application with MobX store. I hope you enjoyed the post and found it useful.

Originally published at qaiser.com.au.

Originally published at qaiser.com.au .

翻译自: https://www.freecodecamp.org/news/real-world-reactnative-apps-made-easy-with-react-native-elements-jest-and-mobx-mst-15003ccefef1/

mobx在react中应用

mobx在react中应用_借助React Native Elements,Jest和MobX MST可以轻松实现现实世界中的ReactNative应用...相关推荐

  1. 游戏ai人工智能_为什么游戏AI无法帮助AI在现实世界中发挥作用,但可以

    游戏ai人工智能 多人游戏被视为一个硕果累累的竞技场,在其中可以模拟许多现实世界中的AI应用程序场景(例如自动驾驶汽车,无人驾驶无人机和协作商务),这些场景可能过于昂贵,投机性或冒险性,无法在现实世界 ...

  2. 印度软件水平为什么世界第一_第1部分:为什么现实世界中的软件需求很难

    印度软件水平为什么世界第一 这是我 过去几年 与 Healthforge 团队一起在医疗保健领域开发软件的经验系列文章中的第一 篇 . 在大多数时间里,我们一直与欧洲,北美和澳大利亚的主要中心以及全球 ...

  3. Java:现实世界中最流行的10个Java应用程序示例

    Java 是 DevOps.AI.机器学习和微服务的第一大编程语言.今天,Java 广泛用于企业应用程序和构建动态数字产品.它也是增强和虚拟现实.大数据和持续集成的有用技术.Java 生态系统是使用先 ...

  4. 12个现实世界中的机器学习真相

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 作者:Delip 编译:ronghuaiyang 导读 当你在现实 ...

  5. 《嵌入式系统数字视频处理权威指南》——第1章 现实世界中的视频

    本节书摘来自华章计算机<嵌入式系统数字视频处理权威指南>一书中的第1章,作者:(美)Michael Parker Suhel Dhanani 更多章节内容可以访问云栖社区"华章计 ...

  6. 为什么游戏AI无法帮助AI在现实世界中发挥作用,但可以

    多人游戏被视为一个硕果累累的竞技场,可以在其中模拟许多现实世界中的AI应用程序场景(例如自动驾驶汽车,无人驾驶无人机和协作商务),这些场景可能过于昂贵,投机性或冒险性,无法在现实世界中进行全面测试. ...

  7. 现实世界中的Windows Azure:澳大利亚的体育博彩公司为赛马微型网站押注Windows Azure

    作为现实世界中的Windows Azure系列中的一部分,我联系了Centrebet公司的网络运营经理Shane Paterson,来了解该公司如何运用Windows Azure 建立一个专用的春季赛 ...

  8. 现实世界中哪些地方用到了Java?

     现实世界中哪些地方用到了Java? java android应用 电子商务 编程语言 应用程序 操作系统 除了Minecraft这款游戏以外,你有没有见过用Java编写的游戏.桌面系统.办公软件 ...

  9. 小机器人在现实世界中学会快速驾驶

    小机器人在现实世界中学会快速驾驶 -强化学习加上预训练让机器人赛车手加速前进- Without a lifetime of experience to build on like humans hav ...

最新文章

  1. 将论文中的所有参考文献编号批量上标化
  2. 编程之美2.17 数组循环移位
  3. linux 权限管理 lvm,Linux系统中RAID及LVM管理
  4. python的编程模式-Python 编程,应该养成哪些好的习惯?
  5. css行高line-height的一些深入理解及应用
  6. 电脑系统修复有多重要?
  7. Tomcat源码解析六:Tomcat类加载器机制
  8. Apicloud开发之V7包继承AppCompactActivity后云编译资源找不到的解决办法
  9. 二维有限元方程matlab,有限元法求解二维Poisson方程的MATLAB实现
  10. 文本分类--情感分析
  11. TCP 连接中的TIME_WAIT
  12. ADODB.Stream 错误 '800a0bbc' 写入文件失败
  13. 并查集 | 1107
  14. socket编程之TCP/UDP
  15. php去掉指定字符串,php如何删除字符串中的指定字符串
  16. 【动画消消乐 】一个小清新类型的全局网页过渡动画 075
  17. 你知道现在有多少AI开放平台吗?
  18. 短视频运营小技巧,掌握推荐机制很重要,吸粉引流也不难
  19. 【多轮对话】任务型多轮对话数据集和采集方法
  20. ora-01652无法通过128(在表空间temp中)扩展temp段

热门文章

  1. [UTCTF2020]basic-crypto
  2. 鸿蒙应用开发DevEco运行时出现java.io.IOException: Invalid keystore format
  3. If you have database settings to be loaded from a particular profile you may之oss文件上传遇到的问题
  4. java深入微服务原理改造房产销售平台,Java深入微服务原理改造房产销售平台
  5. websocket 占用 端口_WebSocket断开原因分析,再也不怕为什么又断开了
  6. 荷兰海牙旅游景点,让你领略欧洲的美丽风光
  7. 赛效:怎么在线给Word文档加图片水印
  8. Flash9.ocx彻底删除的最佳方法
  9. (附源码)计算机毕业设计SSM基于的在线怀旧电影歌曲听歌系统
  10. 史上最全的Excel导入导出之easyexcel