本文记录Taro开发H5项目中存在的一些问题,不局限于Taro本身,其他方面的问题也记录在此
1 设置镜像源
mirror-config-china
mirror-config-china 会在 npm用户配置文件(~/.npmrc)写入一系列镜像配置,包括registry=https://registry.npmjs.org,
如果你想切换到官方npm源,请用命令npm config set registry https://registry.npmjs.org
如果你项目中用的
yarn,那么mirror-config-china这个包好像就没啥用了,因为yarn修改配置是用的.yarnrc,而不是.npmrc
2 内置环境变量
process.env.TARO_ENV
weappswanalipayh5rnttqqquickapp
3 小程序原生作用域获取
一般我们需要获取 Taro 的页面和组件所对应的小程序原生页面和组件的实例,这个时候我们可以通过 this.$scope 就能访问到它们。
4 eslint调整
4.1 项目调整
主要将config以及mobx componentWillReact 加入顺序中
1 | "react/sort-comp": [ |
4.2 自定义eslint规则
由于Taro里的组件都是开头大写字母,由此我们可以写一条eslint规则来自动转首字母大写。
github地址
5 stylelint配置
6 双向绑定设置
由于Taro不能像小程序setData{'a.b.c':value}设置key数据路径的形式,这里写了一个方法
1 | const mergeWith = require('./lodash.mergewith') |
使用方法:onInput={handleInput.bind(this, "a.b.c")},这样就可以设置this.state.a.b.c的值了
7 Taro更新问题
windows系统建议使用管理员权限运行cmd窗口- 建议
npm i -g @tarojs/cli@latest更新,不使用taro update self(试过两次均不成功)
8 微信公众号相关问题
- 101-webpack怎么使用微信sdk
- 微信公众号登录:跳转认证页时
redirect_uri参数必须encodeURIComponent转码
1 | getAppId(showLoading).then(appid => { |
9 H5页面使用HOC,无法触发componentDidShow
目前,在h5端实现HOC的componentDidShow会比较麻烦。由于router只触发了页面组件的componentDidShow,换句话说,只会触发最外层的组件的componentDidShow,所以需要手动在最外层高阶组件的componentDidShow中手动调用子组件对应的生命周期。
– issues
HOC组件:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15function 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} />
}
}
}
}
tryToCall.js1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16/**
* 尝试调用函数
*
* @param {function} func 调用的函数
* @param {any} ctx 调用上下文
* @param {...any} args 函数调用参数
* @returns {any} returnValue
*/
export const tryToCall = (func, ctx = null, ...args) => {
if (!func) return
if (ctx) {
return func.apply(ctx, args)
} else {
return func(...args)
}
}
注意,如果使用了
Mobx,请将HOC组件设置在最外层
1
2
3
4 > @title("课程详情") // 请将HOC组件设置在最外层
> @inject('loginStore','userStore')
> @observer
>