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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

zhangxiaobin   2020-05-07 我要评论

作者: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: '/pageshttps://img.qb5200.com/download-x/demohttps://img.qb5200.com/download-x/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: '/pageshttps://img.qb5200.com/download-x/demohttps://img.qb5200.com/download-x/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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们