This article documents some of the problems with the development of the H5 project, not only Taro itself, but also other aspects
1 Set the image source
mirror-config-china
Mirror – config – China will once the user configuration file (~ /. NPMRC) to write a series of mirror configuration, including registry=https://registry.npmjs.org, If you want to switch to the official source of NPM, please use the command NPM config set registry at https://registry.npmjs.org
If you use yarn in your project, mirror-config-china is useless, because yarn modifiers use.yarnrc instead of.npmrc
2 Built-in environment variables
process.env.TARO_ENV
weapp
swan
alipay
h5
rn
tt
qq
quickapp
Applets native scope acquisition
Usually, we need to obtain the native pages and components of the applet corresponding to the Taro pages and components. In this case, we can access them through this.$scope.
Official document
4 eslint adjustment
4.1 Project Adjustment
Add config and Mobx componentWillReact to the order
"react/sort-comp": [1, {"order": [
"/^config$/"."static-methods"."lifecycle"."everything-else"."render"]."groups": {
"lifecycle": [
"displayName"."propTypes"."contextTypes"."childContextTypes"."mixins"."statics"."defaultProps"."constructor"."getDefaultProps"."state"."getInitialState"."getChildContext"."getDerivedStateFromProps"."componentWillMount"."UNSAFE_componentWillMount"."componentWillReact"."componentDidMount"."componentWillReceiveProps"."UNSAFE_componentWillReceiveProps"."shouldComponentUpdate"."componentWillUpdate"."UNSAFE_componentWillUpdate"."getSnapshotBeforeUpdate"."componentDidUpdate"."componentDidCatch"."componentWillUnmount"]}}]Copy the code
4.2 Customizing ESLint Rules
Since the components in Taro start with an uppercase letter, we can write an ESLint rule to uppercase the first letter. Making the address
5 stylelint configuration
Refer to my other article
6 Bidirectional binding Settings
Since Taro cannot set the key data path in the form of the setData{‘ A.B.C ‘:value} applet, we write a method here
const mergeWith = require('./lodash.mergewith'/** @input * 'onInput={handleinput.bind (this,"a.b.c")}`
*
* @tutorial https://github.com/NervJS/taro/issues/2642
*/
export function handleInput(keyName, event) {
let value = event.detail.value
let arr = keyName.split(".")
let key = arr.shift()
let obj = this.state[key]
if(! arr.length){ this.setState({ [key]: value })return value
}
let reverseArr=arr.reverse()
let sourceObj={}
let tmp={}
for (let i = 0; i < reverseArr.length; i++) {
if(i==0){
tmp[arr[i]]=value
sourceObj=tmp
}else{
sourceObj={}
sourceObj[arr[i]]=tmp
tmp=sourceObj
}
}
/**
* @see
* https://www.lodashjs.com/docs/latest#_mergewithobject-sources-customizer* * /function customizer(objValue, srcValue) {
if(Array.isArray(objValue)){
return srcValue
}
}
let re=mergeWith({},obj,sourceObj,customizer)
this.setState({ [key]: re })
return value
}
Copy the code
Handleinput.bind (this, “A.B.C “)} to set this.state.a.b.c
7 Taro update questions
windows
You are advised to run the system with administrator rightscmd
window- advice
npm i -g @tarojs/cli@latest
Update, not usedTaro Update Self (try twice without success)
8. Questions related to wechat official accounts
- 101- How does Webpack use wechat SDK
- Wechat public account login: jump authentication page
redirect_uri
Parameters must beencodeURIComponent
transcoding
Then (appID => {// redirect_uri must encodeURIComponent transcoding var URL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=snsapi_userinfo&state=${Math.floor(Math.random()*1000)}#wechat_redirect`
window.location.replace(url)
})
Copy the code
9 H5 pages use HOC and cannot trigger componentDidShow
Currently, implementing HOC’s componentDidShow on the H5 side can be cumbersome. Since the Router triggers only componentDidShow for the page component, in other words, only componentDidShow for the outermost component, you need to manually invoke the life cycle of the child component in the outermost component’s componentDidShow. — issues
HOC components:
function title(iTitle=' ') {
return function (WrappedComponent){
return class extends Component{
static displayName=`title(${WrappedComponent.displayName}) `componentDidShow(){
tryToCall(this.wrappedRef.componentDidShow, this.wrappedRef)
}
render() {return<WrappedComponent ref={ref => { this.wrappedRef = ref }} {... this.props} /> } } } }Copy the code
tryToCall.js
/** * try to call the function ** @param {function} func call function * @param {any} CTX call context * @param {... Any} args function call argument * @returns {any}returnValue
*/
exportconst tryToCall = (func, ctx = null, ... args) => {if(! func)return
if (ctx) {
return func.apply(ctx, args)
} else {
returnfunc(... args) } }Copy the code
Note that if you are using Mobx, place the HOC component on the outermost layer
@title("Course Details"// Set the HOC component on the outermost @inject('loginStore'.'userStore') @observer Copy the code
10 Verifying the route permission
Immediately following the above little point, HERE I use HOC component to set, the user token is saved in Mobx, to judge whether the user logs in or not, if not, jump to the login page
function login(WrappedComponent){
return class extends Component{
static displayName=`login(${WrappedComponent.displayName}) `componentDidShow(){
tryToCall(this.wrappedRef.componentDidShow, this.wrappedRef)
}
render(){
console.log("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- components have been login HOC hijacked -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -")
const {token} = store.loginStore
if (token) {
// ...
return<WrappedComponent ref={ref => { this.wrappedRef = ref }} {... this.props} /> }else{/ /...return null
}
}
}
}
Copy the code
On the page that requires permission authentication (that is, the page that requires login first), write @login at the beginning
@login
class Index extends Component{}
Copy the code
11 H5 scrollIntoView is not set to the top
Using getBoundingClientRect is a handy way to solve this problem
// HACK: Fix H5 setting crollIntoView not topif(process.env.TARO_ENV === 'h5'){
this.setState({tabIndex: value})
setTimeout(() => {
var $tab=document.getElementById("tab")
var $scrView=document.querySelector(".KnowledgeOnlineDetail").querySelector(".scrollview")
var rectTop= $tab.getBoundingClientRect().top
if(rectTop>2 || rectTop<-2){
var sTop= $scrView.scrollTop + rectTop
setTimeout(() => {
$scrViewScrollTo (0 ~ ~ sTop) / / attention ~ ~ is rounded up in negative, positive integer} is down, 0)}}, 200)}Copy the code