【React-Native】解决异步获取measure时获取值的

2019-04-29  本文已影响0人  小面包呀

先来一张热乎的示例图:

hot-img?
step1: 通过设置ref来获取对应的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后把数据统一返回回去,此时发现由于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: {}
}
获取不到measure的值

解决办法:

方法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));
}
上一篇下一篇

猜你喜欢

热点阅读