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


作者: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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM