Home  >  Article  >  Web Front-end  >  Detailed explanation of the steps of combining React with TypeScript and Mobx

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

php中世界最好的语言
php中世界最好的语言Original
2018-05-24 10:53:207097browse

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

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();

页面的编写

这里描述一写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>

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

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

加入Mobx

npm i mobx react-mobx mobx-react-router -S

重新修改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();

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>
@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;
}

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;

然后是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;

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

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

目录结构

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

本项目使用了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:
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