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
- Demonstration of student class check-in applets developed by Taro, Redux
- * Basic use of Taro
- * Considerations for use as a React developer (only in practice)
- Processing in actual development
- Taro and the problems encountered in the development of wechat small program summary
- 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
yarn global add @tarojs/cli
To install the CLI using YARNtaro init myApp
Create 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.npm un dev:weap
Enter the wechat development tool to view their small program.- The specific components and apis are similar to applets. See the Taro documentation to learn more about them.
- And then development is like React. Pay attention to
ComponentDidShow, componentDidMount
Different representations of life cycles in applets. The TAB pagecomponentDidMount
Only 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)
sourcemap
If it doesn’t work, it’s XXXXX- Can’t deconstruct the pass value, need
key value
Pass to child components - Not in the
render
Besides writingjsx
this.props
The function passed muston
ordispatch
At the beginning- From the parent component
props
, must be defined instatic defaultProps
In, otherwise can not get componentDidMount
In wechat/Baidu/Bytedance/Alipay applet, this life cycle method corresponds to app’sonLaunch
componentDidShow
In wechat/Baidu/Bytedance/Alipay applet this life cycle method correspondsonShow
componentDidHide
In wechat/Baidu/Bytedance/Alipay applet this life cycle method correspondsonHide
- Single quotes must be written in JS code, especially in JSX. Double quotes may cause compilation errors
- The environment variable
process.env
Don’t deconstruct it to get throughenv
Configuration of theprocess.env
Environment variables, please write them in fullprocess.env.NODE_ENV
To use - use
this.$componentType
To judge the presentTaro.Component
Whether it is a page or a componentPAGE
和COMPONENT
- Stateless components are not supported
- Cannot be added to a file containing JSX elements
map
Use in circulationif
expression - You can’t use
Array#map
Methods outside of the JSX array - To pass functions from a parent component to a child component, the property name must be
on
At 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.