微信小程序
https://github.com/Neilai/Taro-bug
小程序基础库: 2.12.0
使用框架: React
克隆仓库,yarn, yarn dev,然后使用小程序开发工具打开,控制台第一次打印rec为null(ComponentDidMount),点击hello world触发 componentDidUpdate后可以发现元素被成功select到,说明ComponentDidMount中元素还未挂载?那我们应该使用什么生命周期钩子?
import { View, Text } from "@tarojs/components";
import React, { Component } from "react";
import Taro from "@tarojs/taro";
import "./index.scss";
export default class Index extends Component {
state = {
count: 0,
};
componentDidMount() {
Taro.createSelectorQuery()
.select("#testId")
.boundingClientRect((rec) => {
console.log("rec", rec);
})
.exec();
}
componentDidUpdate() {
Taro.createSelectorQuery()
.select("#testId")
.boundingClientRect((rec) => {
console.log("rec", rec);
})
.exec();
}
render() {
return (
<View className='xxx'>
<Text
id='testId'
onClick={() => {
this.setState({
count: this.state.count + 1,
});
}}
>
Hello world!
<br></br>
{this.state.count}
</Text>
</View>
);
}
}
rec第一次打印不为Null
rec为null
Taro CLI 3.0.7 environment info:
System:
OS: macOS 10.14.6
Shell: 5.3 - /bin/zsh
Binaries:
Node: 12.18.2 - ~/.nvm/versions/node/v12.18.2/bin/node
Yarn: 1.22.4 - /usr/local/bin/yarn
npm: 6.14.5 - ~/.nvm/versions/node/v12.18.2/bin/npm
npmPackages:
@tarojs/components: 3.0.7 => 3.0.7
@tarojs/mini-runner: 3.0.7 => 3.0.7
@tarojs/react: 3.0.7 => 3.0.7
@tarojs/runtime: 3.0.7 => 3.0.7
@tarojs/taro: 3.0.7 => 3.0.7
@tarojs/webpack-runner: 3.0.7 => 3.0.7
babel-preset-taro: 3.0.7 => 3.0.7
eslint-config-taro: 3.0.7 => 3.0.7
react: ^16.10.0 => 16.13.1
在 onReady 里试一下
https://nervjs.github.io/taro/docs/react#onready
在 onReady 里试一下
https://nervjs.github.io/taro/docs/react#onready
您好,这解决我的问题,感谢~~
提一个小建议,当时我发现是生命周期的问题,搜了一下文档,然后搜到的是这个https://nervjs.github.io/taro/docs/apis/about/tarocomponent/ 所以没注意到上述文档。
希望能将这个Taro2升taro3的重大改动增加到迁移指南里面,另外taro2升级3我还遇到了canvas的问题,希望您百忙中可以抽空看一下
https://github.com/NervJS/taro/issues/7314
再次感谢
我也遇到这问题了,即使更换为onReady 依然是null 延迟获取可获取到.
window taro:3.0.21
h5端没问题,小程序端为null
Most helpful comment
在 onReady 里试一下
https://nervjs.github.io/taro/docs/react#onready