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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React and the Frontend: Building Interactive Experiences React and the Frontend: Building Interactive Experiences Apr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

Open Intents: Can ERC-7683 become a 'Walmart' supermarket with the intention of synergy between Ethereum chains? Open Intents: Can ERC-7683 become a 'Walmart' supermarket with the intention of synergy between Ethereum chains? Mar 04, 2025 pm 06:24 PM

Written by YBBCapital ResearcherAc-Core: Ethereum fragmentation problem and OpenIntents framework: ERC-7683's breakthrough method Source: @ethereumfndnL2 and the booming development of DeFi have led to the increasing fragmentation of Ethereum liquidity. Asset liquidity is scattered among L1 and many L2s, and there is a lack of effective interconnection between various platforms, like isolated "small pools", hindering the overall efficiency of Ethereum. In 2024, Ethereum added more than 100 new chains, which is like a large shopping mall with a wide range of products, but it requires settlement in different currencies. To solve this problem, the Ethereum Foundation released OpenIntentsF on February 20

React's Ecosystem: Libraries, Tools, and Best Practices React's Ecosystem: Libraries, Tools, and Best Practices Apr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

See all articles