当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 初识 Remax -- "使用真正的 React 构建小程序(1)

初识 Remax -- "使用真正的 React 构建小程序(1)

2020年05月07日  | 移动技术网IT编程  | 我要评论

作者:zhangxiaobin

创作时间:2020年 3月12日

个人微信公众号:【微新悦】

背景:今天公司要求用react开发小程序。what?我第一反应,react能开发小程序了?作为一个使用了vue长达3年的程序猿的我来说,心里一万只蚂蚱经过。哦?不慌,吃口药,我可以的。怀着半信半疑的心态去百度上搜搜了一下。哇去,还真有。度娘讨论的比较多的是 taro 和 remax。

remax,使用真正的 react 构建小程序 -- 这句话引起我深入探索的兴趣。
为了不浪费读者们的宝贵时间,在下先贴上自己摸索了半天的心得(在下会在本系列文章中,逐步带大家用remax构建一个完善的技术架构,请不要离开,紧跟我的步伐)

                                                            
初识体验:

与原生小程序不同之处,使用了react的语法糖,通过在js-return渲染页面,样式文件通过import引入。
目前还不满意的地方,自定义封装组件,组件之间的引入与参数传递,后面会继续探索。

 

remax官网:  https://remaxjs.org/

 

(1)、remax介绍  -- 来自蚂蚁金服的前端工程师 @边柳
问题1:为什么要用react开发小程序
回答:微信小程序在商业中取得非常大的成功,react本身有庞大的技术生态,可以使用react所有特性,可以愉快的使用typescript。

 

(2)、渲染原理

      小程序中是没有 dom 的,我们写的代码运行在一个与 dom 隔离的独立线程中。remax 在这里引入一层叫 vnode 的抽象层,我们会先把 react 的虚拟 dom 映射到 vnode 上,然后把 vnode 转换成小程序页面的 data,然后在小程序模板里把这个 data显示成界面

 

项目开撸:

 

命令窗口下执行:

$ npx degit remaxjs/template-wechat-typescript my-app
$ cd my-app 

运行项目:

$ npm run dev

核心讲解点:

(1)、app.config.js 为小程序全局配置文件,对应 app.json

            在pages 集合里,配置页面路由

(2)、pages/index/index.js 页面文件,对应小程序 page 方法

import * as react from 'react';
import { view, text } from 'remax/wechat';
import './index.module.css';
export default () => {
return (
<view>
<text>pages/index/index</text>
</view>
);
};

(3)、css预处理器安装

npm install less --save # less 用户
npm install node-sass --save # sass 用户

(4)、页面之间的跳转方式之一

wx.navigateto({

url: '/pages/demo/demo?coed=1'

    })

(5)、http请求封装(基于wx.request)进行promise封装

let wxrequest = (url: string, config: any, resolve, reject) => {

    let {

        data = {},

        contenttype = 'application/json',

        method = 'get',

        ...other

    } = { ...config }

    wx.request({

        url: url,

        data: { ...data },

        method: method,

        header: {

            'content-type': contenttype,

            'cookie': '' // 全局变量中获取 cookie

        },

        success: (data) => {

            console.log(data.statuscode)

            let wx_succes = () => {

                resolve(data)

            }

            let wx_fail = () => {

                const err_code_list = { //常见错误码列表

                    [400]: "请求错误",

                    [401]: "登录失效或在其他地方已登录",

                    [403]: "拒绝访问",

                    [404]: "请求地址出错",

                    [408]: "请求超时",

                    [500]: "服务器内部错误",

                    [501]: "服务未实现",

                    [502]: "网关错误",

                    [503]: "服务不可用",

                    [504]: "网关超时",

                    [505]: "http版本不受支持"

                }

                let statearray = [400, "string", false];

                const errmsg = err_code_list[data.statuscode]

                wx.showtoast({

                    mask: true,

                    title: errmsg,

                    icon: 'none',    //如果要纯文本,不要icon,将值设为'none'

                    duration: 2000

                })

                resolve(false)

            }

            data.statuscode == 200 ? wx_succes() : wx_fail()

 

        },

        fail: (err) => {

            wx.showtoast({

                mask: true,

                title: '请求错误!' + err.errmsg,

                icon: 'none',    //如果要纯文本,不要icon,将值设为'none'

                duration: 2000

            })

            reject(err)

        }

    })

}

export default wxrequest;

组件内的使用如下:pages/index/index

import * as react from 'react';

import { view, text, image } from 'remax/wechat';

import styles from './index.module.css';

import wxrequest from '@/serve/request.ts';

import { useshow, usequery, unstable_usenativeeffect, } from 'remax';

export default () => {

  const [aa, setaa] = react.usestate(aa, 0);

  const [width, setwidth] = react.usestate(width, 0);

  const [height, setheight] = react.usestate(height, 0);

  let handleclick = () => {

    console.log('点击了')

    wx.navigateto({

      url: '/pages/demo/demo?coed=1'

    })

  }

  useshow(() => {

    let url = 'jjjj'

    var promise = new promise((resolve, reject) => {

       wxrequest(url, {}, resolve, reject)

    })

    // return promise

    return promise.then(res => {

      console.log(res)

      setaa(900)

    }).catch(err => {

      console.log(err)

    })

    settimeout(() => {

      setwidth(100)

    }, 3000)

    settimeout(() => {

      setheight(100)

    }, 3000)

  });

  unstable_usenativeeffect(() => {

    console.log('width', width, 'height', height);

    // 只有在 width 变化时,才执行这个逻辑。

    // 建议一定要写 hooks 依赖,否则所有 setdata 回调后,都会在这里执行

  }, [width]);

 

  return (

    <view classname={styles.app}>

      uiii

      <view classname={styles.header} >

        <view >

          <image

            src="https://gw.alipayobjects.com/mdn/rms_b5fcc5/afts/img/a*ogyzsi087zkaaaaaaaaaaabkarqnaq"

            onclick={handleclick}

          />

        </view>

        <view onclick={handleclick} classname={styles.text}>

          编辑{aa} <text classname={styles.path}>src/pages/index/index.tsx</text> 开始

        </view>

      </view>

    </view>

  );

};

这样我们的项目基本上可以愉快的进行开发了,感谢你的阅读,欢迎关注与点赞-----  一个有想法的攻城狮日常发文,欢迎评论互动。

个人微信公众号:【微信悦】

微信公众号原文链接:https://mp.weixin.qq.com/s/lmdaxaj-dpoiqlanks_dsw

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网