uni-app 字节小程序组件created等生命周期触发两次
uni-app 字节小程序组件created等生命周期触发两次
| 开发环境 | 版本号 | 项目创建方式 |
|---|---|---|
| Windows | win10企业版21H1 19043.1165 | HBuilderX |
# 操作步骤:
## page => index.vue
```vue
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text>
</view>
<index-com></index-com>
</view>
</template>
<script>
import IndexCom from '../../components/index/index.vue'
export default {
components: {
IndexCom
},
data() {
return {
title: 'Hello233'
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
components => index.vue
<template>
<text>index-components</text>
</template>
<script>
export default {
data() {
return {}
},
beforeCreate() {
console.log('---beforeCreate---')
},
created() {
console.log('---create----')
},
mounted() {
console.log('---mounted---')
}
}
</script>
<style>
</style>
在字节小程序的开发者工具上created,mounted会触发两次,微信小程序正常。
预期结果:
在字节小程序的效果与微信小程序一致。
实际结果:
在字节小程序的开发者工具上created,mounted会触发两次,微信小程序正常。
bug描述:
页面内组件在字节小程序的开发者工具上created,mounted会触发两次,微信小程序正常。
更多关于uni-app 字节小程序组件created等生命周期触发两次的实战教程也可以访问 https://www.itying.com/category-93-b0.html
7 回复
没人?
没人?
是一直就有还是新出现的?
尝试切换不同的小程序基础库试试
1、刚开始编译未头条小程序,之前没用过 2、最新的10个版本小程序基础库都一样的结果
使用附件的测试工程在 3.1.3 的字节小程序开发工具测试未复现问题
打印日志如下:
App Launch
App Show
IDE调用systemLog
—create----
这是一个已知的字节小程序平台差异问题。在字节小程序中,组件的生命周期确实会触发两次,这主要是由于字节小程序底层实现机制与微信小程序不同。
原因分析: 字节小程序在初始化组件时,会先创建一次组件实例进行预渲染,然后再正式创建实际使用的组件实例,导致生命周期被重复触发。这是字节小程序平台特有的行为。
解决方案:
-
使用条件判断避免重复执行 在生命周期函数中添加标记,确保逻辑只执行一次:
export default { data() { return { _hasCreated: false } }, created() { if (this._hasCreated) return this._hasCreated = true console.log('---create----') // 你的业务逻辑 } } -
使用平台条件编译 针对字节小程序平台做特殊处理:
export default { created() { // #ifdef MP-TOUTIAO if (this.__created__) return this.__created__ = true // #endif console.log('---create----') } }


