React + MobX 入门及实例(二)

来源:互联网 发布:php写学生成绩系统 编辑:程序博客网 时间:2024/06/05 18:56

在上一章 React + MobX 入门及实例(一) 应用实例TodoList的基础上
1. 增加ant-design优化界面
2. 增加后台express框架,mongoose操作。
3. 增加mobx异步操作fetch后台数据。

步骤

Ⅰ. ant-design

  1. 安装antd包

    npm install antd –save

  2. 安装antd按需加载依赖

    npm install babel-plugin-import –save-dev

  3. 更改.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

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

//expressconst express = require('express');const app = express();//中间件const bodyParser = require('body-parser');app.use(bodyParser.urlencoded({extended: false}));// for parsing application/jsonapp.use(bodyParser.json()); // for parsing application/x-www-form-urlencoded//mongooseconst 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/todosapp.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/addapp.post('/api/todos/add', function(req, res){    todos.create(req.body, function (err) {        res.send(JSON.stringify({status: err? 0 : 1}));    })});//api/todos/removeapp.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

原创粉丝点击