开发者有什么手动优化的方法?
-
开发者可以借助 Taro 提供的各种工具对程序性能进行优化。
预加载
在微信小程序中,从调用
Taro.navigateTo
、Taro.redirectTo
或Taro.switchTab
后,到页面触发 componentWillMount 会有一定延时。因此一些网络请求可以提前到发起跳转前一刻去请求。Taro 提供了
componentWillPreload
钩子,它接收页面跳转的参数作为参数。可以把需要预加载的内容通过return
返回,然后在页面触发 componentWillMount 后即可通过this.$preloadData
获取到预加载的内容。注意:调用跳转方法时需要使用绝对路径,相对路径不会触发此钩子。
class Index extends Component { componentWillMount () { console.log('isFetching: ', this.isFetching) this.$preloadData .then(res => { console.log('res: ', res) this.isFetching = false }) } componentWillPreload (params) { return this.fetchData(params.url) } fetchData () { this.isFetching = true ... } }
在小程序中,可以使用 this.$preload 函数进行页面跳转传参
用法:
this.$preload(key: String | Object, [ value: Any ])
之所以命名为 $preload,因为它也有一点预加载数据的意味。
如果觉得每次页面跳转传参时,需要先把参数 stringify 后加到 url 的查询字符串中很繁琐,可以利用
this.$preload
进行传参。另外如果传入的是下一个页面的数据请求 promise,也有上一点提到的“预加载”功能,也能够绕过 componentWillMount 延时。不同点主要在于代码管理,开发者可酌情使用。
例子:
// 传入单个参数 // A 页面 // 调用跳转方法前使用 this.$preload this.$preload('key', 'val') Taro.navigateTo({ url: '/pages/B/B' }) // B 页面 // 可以于 this.$router.preload 中访问到 this.$preload 传入的参数 componentWillMount () { console.log('preload: ', this.$router.preload.key) }
// 传入多个参数 // A 页面 this.$preload({ x: 1, y: 2 }) Taro.navigateTo({ url: '/pages/B/B' }) // B 页面 componentWillMount () { console.log('preload: ', this.$router.preload) }
shouldComponentUpdate
当你清楚在某些情况下组件不需要被重新渲染时,可以通过在
shouldComponentUpdate
钩子里返回 false 来跳过本次渲染流程。shouldComponentUpdate (nextProps, nextState) { if (this.props.color !== nextProps.color) { return true } if (this.state.count !== nextState.count) { return true } return false }
Taro.PureComponent
在大多数情况下,开发者可以让组件继承于
Taro.PureComponent
类,而无需手动实现shouldComponentUpdate
。Taro.PureComponent
里实现了shouldComponentUpdate
,它会把新旧 props 和新旧 state 分别做一次浅对比,以避免不必要的渲染。