Table of Contents
Why use TypeScript
Detect errors
Abstract
Documentation
Why use Mobx
Comparison between MobX and Redux
Use Create-React-App to build a TypeScript environment
加入React-Router
路由配置使用姿势
页面的编写
加入Mobx
重新修改index.tsx的入口配置
Container容器的修改
组件的接口定义
Store的配置
目录结构" >目录结构
Home Web Front-end JS Tutorial Detailed explanation of the steps of combining React with TypeScript and Mobx

Detailed explanation of the steps of combining React with TypeScript and Mobx

May 24, 2018 am 10:53 AM
react typescript

This time I will bring you a detailed explanation of the steps of combining React with TypeScript and Mobx. What are the precautions for combining React with TypeScript and Mobx? The following is a practical case, let's take a look.

Detailed explanation of the steps of combining React with TypeScript and Mobx

Why use TypeScript

Detect errors

Through static type detection, hidden logical errors in the program can be detected as early as possible. For JavaScript, although the flexibility of dynamic weakly typed languages ​​is high, for beginners, if they are not familiar with the internal language mechanism of JavaScript, it is easy to cause hidden accidents. However, these problems can be avoided through TypeScript's static type detection, because it can constrain the types of variables. Combined with IDEEditor, you can deduce the type corresponding to the variable and the internal structure, improving the robustness and maintainability of the code.

Abstract

The type system can strengthen standardized programming, and TypeScript provides definition interfaces. It is very important when developing large and complex application software. A system module can be abstractly regarded as an interface defined by TypeScript. Let the design be separated from the implementation, and finally reflect an IDL (Interface Define Language), allowing programming to return to its essence.

Documentation

TypeScript can automatically generate documents based on type annotations, and there is no need to write comments for simple function implementations.

Why use Mobx

Comparison between MobX and Redux

First of all, you must understand that the positioning of mobx and redux is different. Redux manages the entire closed loop of (STORE -> VIEW -> ACTION), while mobx only cares about the STORE -> VIEW part.

Redux advantages and disadvantages:

  • The data flow flows naturally, because any dispatch will trigger a broadcast, and the update granularity is controlled based on whether the object reference changes.

  • By making full use of the feature of time backtracking, business predictability and error location capabilities can be enhanced.

  • Time backtracking is expensive because the reference must be updated every time, unless the code complexity is increased or immutable is used.

  • Another cost of time backtracking is that action and reducer are completely disconnected, because backtracking necessarily cannot guarantee a reference relationship.

  • Introducing middleware to solve the side effects caused by asynchronous, business logic is more or less mixed with magic.

  • Flexible use of middleware can accomplish many complex tasks through agreements.

  • Difficulty supporting typescript.

Mobx advantages and disadvantages:

  • The data flow is unnatural. Only the data used will trigger binding and local accurate updates, but Avoid the trouble of granular control.

  • There is no time back capability because there is only one reference to the data. There is one reference throughout, no immutable required, and no additional overhead of copying objects.

  • Data flow is completed by function calls in one go, making it easy to debug.

  • Business development is not a mental job, but a physical job, less magic and more efficiency.

  • Because there is no magic, there is no middleware mechanism, and there is no way to speed up work efficiency through magic (magic here refers to the process of distributing actions to reducers).

  • Perfectly supports typescript.

SO: If the front-end data flow is not too complex, use Mobx because it is clearer and easier to maintain; if the front-end data flow is extremely complex, it is recommended to use Redux with caution and slow it down through middleware Huge business complexity

Use Create-React-App to build a TypeScript environment

npm i -g create-react-app
create-react-app tinylog-ui --scripts-version=react-scripts-ts
cd tinylog-ui/
npm start
npm run eject
Copy after login

TPS: The last command uses eject to expose all built-in configurations

Passed create-react-app can easily complete the environment initialization of the entire project. If you are willing to toss the environment of TypeScript and webpack, you can try it. The environment building process of webpack and TypeScript is ignored here, and create-react-app is used to implement the environment building. .

加入React-Router

单页应用怎么可以没有前端路由呢,所以我们要加入React-Rotuer, 这里使用的React-Router的版本是v4.2.0

路由配置使用姿势

对于React-Router,这里使用到的模块有Router, Route, Switch

React Router 是建立在 history 之上的。 简而言之,一个 history 知道如何去监听浏览器地址栏的变化, 并解析这个 URL 转化为 location 对象, 然后 router 使用它匹配到路由,最后正确地渲染对应的组件。

代码如下:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Router, Route, Switch } from 'react-router';
import { createBrowserHistory } from 'history';
import registerServiceWorker from './registerServiceWorker';
import { Root } from './containers/Root';
import './index.css';
import Container from './containers/Container';
import SignIn from './containers/Auth/signIn';
import SignUp from './containers/Auth/signUp';
const history = createBrowserHistory();
ReactDOM.render(
  <root>
    <router>
      <switch>
        <route></route>
        <route></route>
        <route></route>
      </switch>
    </router>
  </root>,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();
Copy after login

页面的编写

这里描述一写Container这个组件的编写

import * as React from 'react';
import Header from '../../layout/Header';
import { IAuth } from '../../interfaces';
import { Route, Switch } from 'react-router';
import App from '../App';
import Website from '../Website';
// 这部分是坑点,一开始不知道配置,后发现react-rotuer的4.0版本下需要配置prop的接口
interface Container extends RouteComponentProps {
}
class Container extends React.Component<container> {
  render () {
    return (
      <p>
        <header></header>
        <switch>
          <route></route>
          <route></route>
        </switch>
      </p>
    )
  }
}
export default Container;</container>
Copy after login

这样,当我们访问url为'/'的时候,默认会进入Container,其中Container里面是一层子页面,会匹配url,如果url为'/website', 则进入Website页面,若为'/',则进入App页面。

具体关于React-Router的使用请阅读React-Router文档

加入Mobx

npm i mobx react-mobx mobx-react-router -S
Copy after login

重新修改index.tsx的入口配置

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Router, Route, Switch } from 'react-router';
import { createBrowserHistory } from 'history';
import { useStrict } from 'mobx';
import { Provider } from 'mobx-react';
import { RouterStore, syncHistoryWithStore } from 'mobx-react-router';
// 定义需要使用到的store来进行数据状态的管理
import { 
  TokenStore, 
  AuthStore, 
  HostStore, 
  OverViewStore,
  AssetsStore,
  CommonDataStore,
  PageStore,
  RealTimeStore  
} from './stores';
import registerServiceWorker from './registerServiceWorker';
import { Root } from './containers/Root';
import './index.css';
import Container from './containers/Container';
import SignIn from './containers/Auth/signIn';
import SignUp from './containers/Auth/signUp';
// 引入Echarts
import './macarons';
import 'echarts/map/js/world';
// 开启mobx的严格模式,规范数据修改操作只能在action中进行
useStrict(true);
const browserHistory = createBrowserHistory();
const routerStore =  new RouterStore();
// 同步路由与mobx的数据状态
const history = syncHistoryWithStore(browserHistory, routerStore);
const rootStore = {
  token: new TokenStore(),
  auth: new AuthStore(),
  host: new HostStore(),
  overview: new OverViewStore(),
  assets: new AssetsStore(),
  commmon: new CommonDataStore(),
  page: new PageStore(),
  realtime: new RealTimeStore(),
  router: routerStore
};
ReactDOM.render(
  <provider>
    <root>
      <router>
        <switch>
          <route></route>
          <route></route>
          <route></route>
        </switch>
      </router>
    </root>
  </provider>,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();
Copy after login

Container容器的修改

import * as React from 'react';
import Header from '../../layout/Header';
import { IAuth } from '../../interfaces';
import { Route, Switch } from 'react-router';
// 使用inject和observer来进行数据监听和数据依赖声明
import { inject, observer } from 'mobx-react';
import App from '../App';
import Website from '../Website';
interface Container extends IAuth {
}
@inject('router', 'auth')
@observer
class Container extends React.Component<container> {
  render () {
    return (
      <p>
        <header></header>
        <switch>
          <route></route>
          <route></route>
        </switch>
      </p>
    )
  }
}
export default Container;</container>
Copy after login
@observable 可以在实例字段和属性 getter 上使用。 对于对象的哪部分需要成为可观察的,@observable 提供了细粒度的控制。

@inject 相当于Provider 的高阶组件。可以用来从 React 的context中挑选 store 作为 prop 传递给目标组件

组件的接口定义

import { RouteComponentProps } from 'react-router';
import {
  RouterStore,
  AuthStore
} from '../stores';
export interface IBase extends RouteComponentProps {
  router: RouterStore;
}
export interface IAuth extends IBase {
  auth: AuthStore;
}
Copy after login

Store的配置

先看一下RouterStore:

import { History } from 'history';
import { RouterStore as BaseRouterStore, syncHistoryWithStore } from 'mobx-react-router';
// 路由状态同步
class RouterStore extends BaseRouterStore {
  public history;
  constructor(history?: History) {
    super();
    if (history) {
      this.history = syncHistoryWithStore(history, this);
    }
  }
}
export default RouterStore;
Copy after login

然后是AuthStore:

import { ISignIn, ISignUp } from './../interfaces/index';
import { observable, action } from 'mobx';
import api from '../api/auth'; 
import { IUser } from '../models';
// 登录注册状态
class AuthStore {
  @observable token;
  @observable id;
  @observable email;
  constructor () {
    this.id = '';
    this.token = '';
    this.email = '';
  }
  setLocalStorage ({ id, token, email }: IUser) {
    localStorage.setItem('id', id);
    localStorage.setItem('token', token);
    localStorage.setItem('email', email);
  }
  clearStorage () {
    localStorage.clear();
  }
  @action async signIn (data: ISignIn) {
    try {
      const { data: res } = await api.signIn(data);
      this.id = res.data.id;
      this.token = res.data.token;
      this.email = res.data.email;
      this.setLocalStorage({
        id: this.id,
        token: this.token,
        email: this.email
      });
      return res;
    } catch (error) {
      return error;
    }
  }
  
  @action async signUp (data: ISignUp) {
    try {
      const { data: res } = await api.signUp(data);
      this.id = res.data.id;
      this.token = res.data.token;
      this.email = res.data.email;
      this.setLocalStorage({
        id: this.id,
        token: this.token,
        email: this.email
      });
      return res;
    } catch (error) {
      return error;
    }
  }
  @action signOut () {
    this.id = '';
    this.token = '';
    this.email = '';
    this.clearStorage()
  }
}
export default AuthStore;
Copy after login

Auth是用于网站的登录注册事件以及对应的Token的数据状态保存,登录注册事件的接口请求等操作。

具体的有关Mobx的用法请阅读Mobx文档

目录结构

app
├── api             后端提供的接口数据请求
├── components      编写的可复用组件
├── config          侧边栏以及导航栏配置
├── constants       常量编写
├── interfaces      接口编写
├── layout          布局外框
├── stores          mobx的数据状态管理
├── index.css       全局样式
├── index.tsx       页面入口
├── reset.css       浏览器重置样式
Copy after login

本项目使用了Ant-Design来作为依赖的组件库,具体怎么使用以及配置请参考Ant-Design

到这里其实以及完成对React下TypeScript结合React-Router和Mobx的配置。具体的业务模块如何编写有兴趣可以参阅项目tinylog-ui

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Chart.js轻量级图表库使用案例解析

centos搭建ghost博客步骤分享

The above is the detailed content of Detailed explanation of the steps of combining React with TypeScript and Mobx. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to build a fast data analysis application using React and Google BigQuery How to build a fast data analysis application using React and Google BigQuery Sep 26, 2023 pm 06:12 PM

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to package and deploy front-end applications using React and Docker How to package and deploy front-end applications using React and Docker Sep 26, 2023 pm 03:14 PM

How to use React and Docker to package and deploy front-end applications. Packaging and deployment of front-end applications is a very important part of project development. With the rapid development of modern front-end frameworks, React has become the first choice for many front-end developers. As a containerization solution, Docker can greatly simplify the application deployment process. This article will introduce how to use React and Docker to package and deploy front-end applications, and provide specific code examples. 1. Preparation Before starting, we need to install

How to build real-time data processing applications using React and Apache Kafka How to build real-time data processing applications using React and Apache Kafka Sep 27, 2023 pm 02:25 PM

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and

See all articles