React-Native + Mobx一步步構建項目

前言

前提是你已經搭好環境,而且能跑起來;
不然的話先進行:Mac環境搭建,目標:ios javascript

本項目使用的依賴:java

"dependencies": {
    "lodash": "^4.17.5",
    "mobx": "^4.1.0",
    "mobx-react": "^5.0.0",
    "native-base": "^2.3.5",
    "react": "^16.3.0-alpha.1",
    "react-native": "0.54.4",
    "react-navigation": "^1.5.8"
  },

準備工做

1. 安裝相應依賴:mobx 和 mobx-react;

npm i mobx mobx-react --save

2. 安裝一些 babel 插件,以支持 ES7 的 decorator 特性:

npm i babel-plugin-transform-decorators-legacy babel-preset-react-native-stage-0 --save-dev

3. 打開 .babelrc 沒有就建立一個,配置 babel 插件:

touch .babelrc

寫入:react

{
 'presets': ['react-native'],
 'plugins': ['transform-decorators-legacy']
}

補充:ES7裝飾器語法在編譯器可能會報錯;我這裏用的是vscode,分享解決辦法:ios

  1. 找到 首選項 > 設置 > 工做區設置;
  2. 加入如下代碼:
"javascript.implicitProjectConfig.experimentalDecorators": true

clipboard.png

至此準備工做已經差很少了,接下來寫代碼。。。npm


加入Mobx

1. 根目錄下新建 js文件夾; js下新建store文件夾;

2. store下新建index.js 做用是合併每一個store到一個store中去,最終經過 <Provider {...store}>方式注入<App/>;

3.分別在store下新建幾個js,示例:

// home
import { observable, action } from "mobx";

class HomeStore {
  @observable text; // 註冊變量,使其成爲可檢測的
  @observable num;

  constructor() {
    this.num = 0; // 初始化變量,能夠定義默認值
    this.text = "Hello, this is homePage!!!";
  }

  @action  // 方法推薦用箭頭函數的形式
  plus = () => {
    this.num += 1;
  };

  @action
  minus = () => {
    this.num -= 1;
  };
}

const homeStore = new HomeStore(); 

export { homeStore };
// user
import { observable, action } from "mobx";

class UserStore {
  @observable userInfo;
  @observable text;

  constructor() {
    this.userInfo = "123";
    this.text = "Hello, this is UserPage!!!";
  }

  @action
  getListData = () => {
    fetch(`http://yapi.demo.qunar.com/mock/5228/record/list`)
      .then(
        action("fetchRes", res => {
          return res.json();
        })
      )
      .then(
        action("fetchSuccess", data => {
          return (this.userInfo = data);
        })
      )
      .catch(
        action("fetchError", e => {
          console.log(e.message);
        })
      );
  };
}

const userStore = new UserStore();

export { userStore };

4. 經過index文件合併:

import { homeStore } from "./home";
import { saleStore } from "./sale";
import { userStore } from "./user";

const store = { homeStore, saleStore, userStore };

export default store;

5. 在組件中使用Mobx:

js目錄下新建tabs文件夾,新建HomeScreen.jsjson

import React, { Component } from "react";
import { View, Text, StyleSheet, TouchableOpacity } from "react-native";
import { connect } from "mobx-react";
import { observer, inject } from "mobx-react";
import { Button, Container } from "native-base";
import Headers from "../common/components/header";

@inject(["homeStore"]) // 注入對應的store
@observer // 監聽當前組件
class HomeScreen extends Component {
  constructor(props) {
    super(props);
    this.store = this.props.homeStore; //經過props來導入訪問已注入的store
    this.state = {
    };
  }

  render() {
    const { text, num } = this.store;
    return (
      <Container>
        <Headers 
        title="首頁" 
        type='index' 
        navigation={this.props.navigation}
        />
        <Text>{text}</Text>
        <Button primary onPress={() => this.store.plus()}>
          <Text>add</Text>
        </Button>
        <Text>{num}</Text>
        <Button primary onPress={() => this.store.minus()}>
          <Text>Minu</Text>
        </Button>
      </Container>
    );
  }
}

export default HomeScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  }
});

6. 目前組件中還拿不到當前組件的store,接下來注入store

在初始化的項目結構中,項目運行的入口文件是index.js,註冊了同級目錄下的App.js;segmentfault

// index.js

import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry.registerComponent('demo', () => App);

因爲須要在App.js上套入store 因此改寫結構,react-native

1. js文件夾下新建App.js

touch App.jsapi

能夠把根目錄下App.js的內容copy過來,而後刪掉根目錄下App.js文件;babel

2. js目錄下新建 setup.js 文件;
import React from "react";
import { Provider } from "mobx-react";
import App from "./App";
import store from "./store";

export default function setup() {
  class Root extends React.Component {
    render() {
      return (
        <Provider {...store}>
          <App />
        </Provider>
      );
    }
  }
  return Root;
}
3. 修改index啓動頁代碼:
import { AppRegistry } from 'react-native';
import setup from "./js/setup";

AppRegistry.registerComponent('******', () => setup());

如今store已經注入,在每一個組件中也能夠拿到當前store的數據了;能夠進行代碼開發了;

相關文章
相關標籤/搜索