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

相关文章
相关标签/搜索