I have not written a small program for a year since I developed a small program for English learning (Smart English Learning) in the native language of small program last year. Recently, I’m going to use the popular Taro(similar to react syntax, multi-end) to develop a class check-in app, check in the hole, feel it.

This article summary
  1. Demonstration of student class check-in applets developed by Taro, Redux
  2. * Basic use of Taro
  3. * Considerations for use as a React developer (only in practice)
  4. Processing in actual development
  5. Taro and the problems encountered in the development of wechat small program summary
  6. TODO

A small check-in program

Function overview: based on geographical location (latitude and longitude) check-in platform. In addition, it includes campus news module, Word information download module, personal information module and so on. Scan code login: Student experience account 123456, password 123456.

Source code stamp here

1. Check in based on Tencent API latitude and longitude

2. Download word information in the news section

3. Personal information module

The basic use of Taro

  1. yarn global add @tarojs/cliTo install the CLI using YARN
  2. taro init myAppCreate a template project (redux, MOBx, and other generator templates can be created by following a set of default commands). And dependencies are then installed by default.
  3. npm un dev:weapEnter the wechat development tool to view their small program.
  4. The specific components and apis are similar to applets. See the Taro documentation to learn more about them.
  5. And then development is like React. Pay attention toComponentDidShow, componentDidMountDifferent representations of life cycles in applets. The TAB pagecomponentDidMountOnly once.

Note: Taro wraps an asynchronous API for applet by default and can be called just like Promise.

// WX
wx.request({
    url: ' 'Data: {}, header: {'content-type': 'application/json'// Default value}, success(res) {}}) // tary.request (url).then(function (res) {
    console.log(res)
})
Copy the code

3. Precautions for use as a React developer (only in practice)

  1. sourcemapIf it doesn’t work, it’s XXXXX
  2. Can’t deconstruct the pass value, needkey valuePass to child components
  3. Not in therenderBesides writingjsx
  4. this.propsThe function passed mustonordispatchAt the beginning
  5. From the parent componentprops, must be defined instatic defaultPropsIn, otherwise can not get
  6. componentDidMountIn wechat/Baidu/Bytedance/Alipay applet, this life cycle method corresponds to app’sonLaunch
  7. componentDidShowIn wechat/Baidu/Bytedance/Alipay applet this life cycle method correspondsonShow
  8. componentDidHideIn wechat/Baidu/Bytedance/Alipay applet this life cycle method correspondsonHide
  9. Single quotes must be written in JS code, especially in JSX. Double quotes may cause compilation errors
  10. The environment variableprocess.envDon’t deconstruct it to get throughenvConfiguration of theprocess.envEnvironment variables, please write them in fullprocess.env.NODE_ENVTo use
  11. usethis.$componentTypeTo judge the presentTaro.ComponentWhether it is a page or a componentPAGECOMPONENT
  12. Stateless components are not supported
  13. Cannot be added to a file containing JSX elementsmapUse in circulationifexpression
  14. You can’t useArray#mapMethods outside of the JSX array
  15. To pass functions from a parent component to a child component, the property name must beonAt the beginning, the above are the problems encountered in the process of use.For more information, please refer to the official documentation

Iv. Processing in actual development

1. Alias can also be used.
// config/index.js
alias: {
    '@actions': path.resolve(__dirname, '.. '.'src/actions'),
    '@assets': path.resolve(__dirname, '.. '.'src/assets'),
    '@components': path.resolve(__dirname, '.. '.'src/components'),
    '@constants': path.resolve(__dirname, '.. '.'src/constants'),
    '@reducers': path.resolve(__dirname, '.. '.'src/reducers'),
    '@style': path.resolve(__dirname, '.. '.'src/style'),
    '@util': path.resolve(__dirname, '.. '.'src/util')},Copy the code
Taro. Requset ()
// feth.js
import Taro from '@tarojs/taro'

const defaultMethod = 'POST'
const successStatus = 200
const successFlag = 1
const messageToast = title => {
    Taro.showToast({
        title,
        icon: 'none',
        duration: 1000
    })
}

export default function fetch(options) {
    const { 
        url,
        method = defaultMethod,
        params,
        showErrorToast = true,
    } = options
    returnRequest ({url, method, data: params,}). Then (response => {const {statusCode, data} = response // Not 200if(statusCode ! = successStatus) {const {error} = data // reject ShowToast is executed in catch. const errMessage = {errMsg: error ||'Failed to request interface'}
            return Promise.reject(errMessage)
        } elseConst {flag, message, data: datas} = dataif (flag == successFlag) {
                return Promise.resolve(datas)
            } else {
                const errMessage = {errMsg: message || 'Process error'}
                return Promise.reject(errMessage)
            }
        }
    }).catch(errors => {
        const { errMsg } = errors
        if (showErrorToast) {
            messageToast(errMsg || 'Request exception')
        }
        const errMessage = errMsg || 'Request exception'
        return Promise.reject(errMessage)
    })
}
Copy the code
3. Click to scroll to the corresponding node
toggleComments = () => {
    Taro.createSelectorQuery().select('#comments-id').boundingClientRect(function(rect){// Scroll the page to the response location taron.pagescrollto ({scrollTop: rect.bottom})}).exec()}Copy the code

Five, Taro and the problems encountered in the development of wechat small program summary

1. Download and preview of doc documents

DownloadFile API, but currently only support long and download pictures, voice, video three types of files. Doc files will be downloaded as temporary path. Myword files, available for preview (Default android phone wechat built-in browser open, can be forwarded to the computer. Ios TBD).

Taro.showLoading()
const params = {
    url,
    fileType: "doc", SUCCESS (res) {// As soon as the server has the response data, it writes the response content to the file and enters the SUCCESS callback. The business needs to determine whether it downloaded the desired contentif (res.statusCode === 200) {
            const wxPath = res.tempFilePath
            Taro.openDocument({
                filePath: wxPath,
                fileType: "doc",
                success: function (ress) {
                    Taro.hideLoading()
                    console.log(ress)
                },
                fail: function (resfo) {
                    Taro.hideLoading()
                    util.showToast('Failed to open document')
                }
            })
        }
    },
    fail: function (resfd) {
        Taro.hideLoading()
        util.showToast('File download failed')
    },
}
Taro.downloadFile(params).then()
Copy the code
2. Obtain geographical location, longitude and latitude for check-in
wx.getLocation({
  type: 'gcj02', // wgs84 returns GPS coordinates, gcj02 returns coordinates available for wx.openLocation success(res) {const {latitude, longitude} = res}})Copy the code

Wx. getLocation requires user authorization before calling. Scope. UserLocation ② When initiating and scanning sign-in, ensure that the type is the same.

// User authorization, app.js configuration item permission: {"scope.userLocation": {
        "desc": "Get user's check-in location"}},Copy the code

3. Can not long press to identify (except small program code) two-dimensional code (TBD)

After previewing the QR code image, qr code recognition is not supported.

getEventData(data, tag) {
    return data.currentTarget.dataset[tag];
},
previewImage = (e) => {
    const current = getEventData(e, 'src') Taro. PreviewImage ({current: current, // HTTP link urls of the current display image: [current] // HTTP link list of images to preview})}Copy the code

Six, TODO

  • Give full play to the advantages of multi-terminal, try other small procedures, H5 and other packaged release.
  • Continue to follow up the download of Word document, and replace the QR code with a small program QR code with parameters (wxacode.getUnlimited)
  • Openid’s impact on multiple endpoints

The tail language

== dish gouge feet, big guy light spray. The content is rough, please correct any questions. == It is necessary to boast that the processing speed of the small program is very fast, and the audit was passed in two hours.