美文网首页React Native实践React NativeReact Native学习
使用react native 创建一个属于你自己的云备忘录app

使用react native 创建一个属于你自己的云备忘录app

作者: mytac | 来源:发表于2018-03-20 14:44 被阅读169次

    效果图

    demo

    app下载地址(android only)

    项目地址

    细化接口

    查询分页

    传入index值,从当前页找到指定条数的数据进行返回。

    这里使用limit()方法返回指定条数;skip()指定跳过的条数。

    修改findDocuments方法:

    // methods/find.js
    const findDocuments = (
      db, data = {}, skipNum = 0, limit = 10,
      collectionName = articleCollection,
    ) =>
      new Promise((resolve, reject) => {
        const collection = db.collection(collectionName);
        collection.find(data).skip(skipNum).limit(limit).toArray((err, docs) => {
          if (err) {
            reject(createError(errors.HANDLE_DB_FAILED));
          } else {
            resolve(createResult(docs));
          }
        });
      });
    

    然后添加一个获取所有文章列表分页的接口

    function getArticles(req, res) {
      const { pageNum, listNum } = req.body;
    
      connectDB
        .then(db => findDocuments(db, {}, pageNum, listNum))
        .then(data => res.json(data))
        .catch((err) => { unknowError(err, res); });
    }
    

    上一篇文章的出的接口都很基础,但在业务上一次调两三个太复杂了,所以在server端我们细化下接口:

    上传

    先看是否传了id字段,有则直接更新,没有则新增(需要自己手动new一个ObjectID,最后用来返回)。更改upload接口:

    if (id && id.length > 0) {
        connectDB
          .then(db => updateDocument(db, { _id: new ObjectID(id) }, { content, title }))
          .then(data => res.json(data))
          .catch((err) => { unknowError(err, res); });
      } else {
        const newId = new ObjectID();
        connectDB
          .then(db => insertDocuments(db, { content, title, _id: newId }))
          .then((data) => {
            const backData = Object.assign(data);
            backData.body.id = newId;
            return res.json(backData);
          })
          .catch((err) => { unknowError(err, res); });
      }
    

    回到Detail组件,新增uploadData函数,用来执行上传操作

     async uploadData() {
        const { content, title } = this.state;
        try {
          const result = await request('/upload', { content, title });
          console.log('result', result);
          // 上传成功
          Toast.show('上传成功', Toast.SHORT);
        } catch (e) {
          Toast.show('上传失败', Toast.SHORT);
        }
      }
    

    本地存储

    这个程序包含三种存储类型,分别为state树,本地存储asyncStorage和远程数据。

    我的第一个想法是,进入主页先从本地获取数据放到state中,进行各种操作,最后退出应用时再存到本地。数据结构为:

    Articles:[{time,title,content},{..},{..}]
    

    在列表页添加getNewData函数,用来获取本地的内容:

    getArticles().then((articles) => {
          this.setState({
            articles,
          });
        });
    

    然后,在跳转到detail路由上的方法中添加几个参数:articles,index,updateArticlearticles是从本地获取的数据,index即为列表项的索引,我们用它来判断是否为新增的条目,updateArticle是用来更新state tree的。

    updateArticle(title, content, index) {
        const { articles } = this.state;
        const newArticle = [].concat(articles); // 注意不要直接修改state!!
        const date = new Date();
        const newData = { time: date.getTime(), title, content };
        if (index) {
          newArticle[index] = newData;
        } else {
          newArticle.push(newData);
        }
        this.setState({
          articles: newArticle,
        });
      }
    

    然后我们在Detail组件中调用传过来的updateArticle函数

    updateArticle(title, content, index) {
        const { articles } = this.state;
        const newArticle = [].concat(articles);
        const date = new Date();
        const newData = { time: date.getTime(), title, content };
        if (index !== undefined) {
          newArticle[index] = newData;
        } else {
          newArticle.push(newData);
        }
        this.setState({
          articles: newArticle,
        });
      }
    

    在跳回List组件时,调用存储函数:

    componentDidUpdate() {
        setArticles(this.state.articles).then((status) => {
          console.log(status);
        });
      }
    

    这里有一个关于AsyncStorage的坑,是在开发时第一次启动app调试模式时,asyncStorage不生效,需要杀掉程序,重新进一下。本人因为这个坑折腾了两天TAT~

    空值处理

    当标题和内容均为空,不保存到本地;
    当只有标题为空时,自动截取内容前6个字符作为标题进行保存;
    当只有内容为空时,直接保存。

    我们在Detail组件中来编写以上步骤:

    ...
      componentWillUnmount() {
        const { isDelete, title, content } = this.state;
        /* eslint-disable no-unused-expressions */
        !isDelete && this.updateArticle();
        // 空值检测
        if (title.length > 0 || content.length > 0) {
          this.updateArticlesToStateTreeAndLocal(this.newArticles);
        }
        this.deEmitter.remove();
        this.deleteEmitter.remove();
      }
      ...
        updateArticle() {
        const { title, content, id } = this.state;
        const newData = { title, content, id };
        if (title.length === 0) {
          newData.title = content.slice(0, 6);
        }
        if (this.index !== undefined) {
          this.newArticles[this.index] = newData;
        } else {
          this.newArticles.push(newData);
        }
      }
      ...
    

    打包

    按照官网描述打包就行~也不是很麻烦,没什么坑。最后别忘了把项目fork后再起下服务器

    cd server
    yarn start
    

    剩下的小细节就不一一赘述了,直接看代码就行了。这个项目不复杂,剩下的功能我会在后面的版本中逐步迭代的~

    有问题或疑问请在评论区指出~~

    前两篇地址:

    使用react native 创建一个属于你自己的云备忘录app~(A。用node搭个服务,基础篇)

    使用react native 创建一个属于你自己的云备忘录app~(B.编写app端)

    相关文章

      网友评论

        本文标题:使用react native 创建一个属于你自己的云备忘录app

        本文链接:https://www.haomeiwen.com/subject/ficbqftx.html