React + MobX 状态管理入门及实例(二)

在上一章 React + MobX 状态管理入门及实例(一) 应用实例TodoList的基础上

  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-dev

  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的安装与配置

  1. 安装express、mongodb、mongoose

npm install --save express mongodb mongoose

  1. 项目根目录创建server.js,撰写后台服务
    引入body-parser中间件,作用是对post请求的请求体进行解析,转换为我们需要的格式。
    引入Promise异步,将多查询分为单个Promise,用Promise.all连接,待查询完成后才会发送查询后的信息,如果不使用异步操作,查询不会及时响应,前端请求的可能是上一次的数据,这不是我们想要的结果。
//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一一对应,主要包含这三个部分:

    @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

源码

Github

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容