React + MobX 入門及實例(二)

在上一章 React + MobX 入門及實例(一) 應用實例TodoList的基礎上html

  1. 增長ant-design優化界面
  2. 增長後臺express框架,mongoose操做。
  3. 增長mobx異步操做fetch後臺數據。

步驟

Ⅰ. ant-design

  1. 安裝antd包

npm install antd --save前端

  1. 安裝antd按需加載依賴

npm install babel-plugin-import --save-devnode

  1. 更改.babelrc 配置爲
{
  "presets": ["react-native-stage-0/decorator-support"],
  "plugins": [
    [
      "import",
      {
        "libraryName": "antd",
        "style": true
      }
    ]
  ],
  "sourceMaps": true
}
  1. 引入antd控件使用
import { Button } from 'antd';

Ⅱ. express, mongodb

前提:mongodb的安裝與配置react

  1. 安裝express、mongodb、mongoose

npm install --save express mongodb mongoosegit

  1. 項目根目錄建立server.js,撰寫後臺服務

引入body-parser中間件,做用是對post請求的請求體進行解析,轉換爲咱們須要的格式。
引入Promise異步,將多查詢分爲單個Promise,用Promise.all鏈接,待查詢完成後纔會發送查詢後的信息,若是不使用異步操做,查詢不會及時響應,前端請求的多是上一次的數據,這不是咱們想要的結果。github

//express
const express = require('express');
const app = express();
//中間件
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));// for parsing application/json
app.use(bodyParser.json()); // for parsing application/x-www-form-urlencoded

//mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todolist',{useMongoClient:true});
mongoose.Promise = global.Promise;
const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log("connect db.")
});

//模型
const todos = mongoose.model('todos',{
    key: Number,
    todo: String
});

//發送json: 數據+數量
let sendjson = {
    data:[],
    count:0
};

//設置跨域訪問
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

//api/todos
app.post('/api/todos', function(req, res){
    const p1 = todos.find({})
        .exec((err, result) => {
            if (err) console.log(err);
            else {
                sendjson['data'] = result;
            }
        });

    const p2 = todos.count((err,result) => {
        if(err) console.log(err);
        else {
            sendjson['count'] = result;
        }
    }).exec();

    Promise.all([p1,p2])
        .then(function (result) {
            console.log(result);
            res.send(JSON.stringify(sendjson));
        });
});

//api/todos/add
app.post('/api/todos/add', function(req, res){
    todos.create(req.body, function (err) {
        res.send(JSON.stringify({status: err? 0 : 1}));
    })
});

//api/todos/remove
app.post('/api/todos/remove', function(req, res){
    todos.remove(req.body, function (err) {
        res.send(JSON.stringify({status: err? 0 : 1}));
    })
});

//設置監聽80端口
app.listen(80, function () {
    console.log('listen *:80');
});
  1. package.json -- scripts添加服務server啓動項
"scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js --env=jsdom",
    "server": "node server.js"
  },

Ⅲ. Fetch後臺數據
先後端交互使用fetch,也一樣寫在store裏,由action觸發。與後臺api一一對應,主要包含這三個部分:mongodb

@action fetchTodos(){
        fetch('http://localhost/api/todos',{
            method:'POST',
            headers: {
                "Content-type":"application/json"
            },
            body: JSON.stringify({
                current: this.current,
                pageSize: this.pageSize
            })
        })
            .then((response) => {
                // console.log(response);
                response.json().then(function(data){
                    console.log(data);
                    this.total = data.count;
                    this._key = data.data.length===0 ? 0: data.data[data.data.length-1].key;
                    this.todos = data.data;
                    this.loading = false;
                }.bind(this));
            })
            .catch((err) => {
                console.log(err);
            })
    }

    @action fetchTodoAdd(){
        fetch('http://localhost/api/todos/add',{
            method:'POST',
            headers: {
                "Content-type":"application/json"
            },
            body: JSON.stringify({
                key: this._key,
                todo: this.newtodo,
            })
        })
            .then((response) => {
                // console.log(response);
                response.json().then(function(data){
                    console.log(data);
                    /*成功添加 總數加1 添加失敗 最大_key恢復原有*/
                    if(data.status){
                        this.total += 1;
                        this.todos.push({
                            key: this._key,
                            todo: this.newtodo,
                        });
                        message.success('添加成功!');
                    }else{
                        this._key -= 1;
                        message.error('添加失敗!');
                    }
                }.bind(this));
            })
            .catch((err) => {
                console.log(err);
            })
    }

    @action fetchTodoRemove(keyArr){
        fetch('http://localhost/api/todos/remove',{
            method:'POST',
            headers: {
                "Content-type":"application/json"
            },
            body: JSON.stringify({
                key: keyArr
            })
        })
            .then((response) => {
                console.log(response);
                response.json().then(function(data){
                    // console.log(data);
                    if(data.status){
                        if(keyArr.length > 1) {
                            this.todos = this.todos.filter(item => this.selectedRowKeys.indexOf(item.key) === -1);
                            this.selectedRowKeys = [];
                        }else{
                            this.todos = this.todos.filter(item => item.key !== keyArr[0]);
                        }
                        this.total -= keyArr.length;
                        message.success('刪除成功!');
                    }else{
                        message.error('刪除失敗!');
                    }
                }.bind(this));
            })
            .catch((err) => {
                console.log(err);
            })
    }

注意

  1. antd Table控件綁定的DataSource是普通數組形式,而通過Mobx修飾器修飾的數組是observableArray,因此要經過observable.toJS()轉換成普通數組。
  2. antd Table控件數據源需包含key,一些對行的操做都依賴key。
  3. 刪除選中項時,必定要在刪除成功後將selectedRowKeys置空,不然在下次選擇時會選中已刪除的項,雖然沒有DOM元素但可能會影響其餘一些操做。
  4. 使用Mobx過程當中,若是this沒法表明自己,而是指向其餘,這時候函數不會執行,也不像React會報錯:this is undefined,這時候須要手動添加bind(this),若是在View試圖中調用時須要綁定,寫爲:bind(store);
  5. 跨域處理JSONP是一種方法,可是最根本的方法是操做header。server.js中設置跨域訪問實際是對header進行匹配。
  6. 若是將mongoose查詢寫爲異步,每一個查詢最後都須要添加.exec(),這樣返回的纔是Promise對象。mongoose易錯

截圖

mobx-demo.gif

源碼

Githubexpress

相關文章
相關標籤/搜索