先來一張熱乎的示例圖:
step1: 通過設(shè)置ref來獲取對應(yīng)的measure值
{list.map(({title, data = []}, i) => (
<View style={styles.container} key={title}>
<Text ref={(r) => (this[title] = r)} style={styles.title}>
{title}
</Text>
{Array.isArray(data) && this.createItem(data, title)}
</View>
))}
step2:在DidMount里獲取measure(為了減少渲染所以想在map后把數(shù)據(jù)統(tǒng)一返回回去,此時發(fā)現(xiàn)由于setTimeout的異步機制使得無法正確賦值)
componentDidMount() {
const res = {};
this.props.list.map(({title}) =>
setTimeout(() => {
this[title].measure((x, y, width, height, left, top) => {
res[title] = {width, height, left, top};
});
})
);
console.log('res', res); // res: {}
}
解決辦法:
方法1:在console.log外層套個setTimeout(總感覺看著很別扭)
setTimeout(() => console.log('res', res), 10);
方法2:使用Promise.all來解決異步問題
componentDidMount() {
const res = {};
const promise = this.props.list.map(
({title}) =>
new Promise((resolve) =>
setTimeout(() => {
this[title].measure((x, y, width, height, left, top) => {
res[title] = {width, height, left, top};
resolve();
});
})
)
);
Promise.all(promise).then(() => console.log('res', res));
}