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

先来一张热乎的示例图:

hot-img?

step1: 通过设置ref来获取对应的measure值

{list.map(({title, data = []}, i) => (
    
         (this[title] = r)} style={styles.title}>
            {title}
        
        {Array.isArray(data) && this.createItem(data, title)}
    
))}

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));
}

你可能感兴趣的:(【React-Native】解决异步获取measure时获取值的问题)