【问题标题】:Can we Call Animated.Timing() after server response?我们可以在服务器响应后调用 Animated.Timing() 吗?
【发布时间】:2020-10-09 04:13:14
【问题描述】:

我有一项任务是在 react-native 中使用动画库以特定方式显示组件。现在对于静态屏幕(没有服务器请求),我发现它很容易实现,因为我使用启动 componentWillMount 类中的 Animation.Timing() 函数和渲染方法,我将使用样式将动画包含在动画。视图。

但是当我在屏幕中使用相同的逻辑时,首先从服务器接收数据,然后以动画格式显示它们。由于在类本身 (componentWillMount) 的初始化期间进行了 Animated.Timing() 调用,因此该逻辑失败。

所以我们怎么能做到这一点对我来说是一个真正的困惑。需要一些指导。

我使用 redux 从服务器获取数据。所以简而言之,我给出了代码的 sn-p。谁能帮我理解我应该在哪里调用 Animated.Timing() 方法

    componentDidMount(){
      this.requestServerforData();
    }
    UNSAFE_componentWillMount(){
        
        //**Change the opacity from 0 to 1 when the server request completes**

        this.visibility = new Animated.Value(0);
        Animated.timing(this.visibility,{
            toValue:1,
            duration:800,
            delay:800,
            useNativeDriver:false
        }).start();
    }

   render(){

       return(
            
                {(this.props.dashboard) ?   // I tried this also not working 
                <ScrollView showsVerticalScrollIndicator={false} style={{marginTop:30}}>
                    
                    
                <Animated.View style={{opacity:this.visibility}}>
                    
                    <View style={styles.GreenTipBackground}>

                    </View>
                </Animated.View>
               </ScrollView> : null }
   }

 const mapstatetoProps = state =>{

    return {  
        dashboard:state.appData.dashboard,
      
    }
 }

【问题讨论】:

  • requestServerforData 在做什么?贴出代码?
  • 它正在向服务器请求数据...在 redux thunk 中。一旦我收到数据,就会调用 mapstatetoProps 在屏幕上显示该数据。我已经分享了
  • 您可以使用componentDidUpate 并检查仪表板中的更改并在那里开始您的动画。 componentWillMount 发生在 componentDidMount 之前,不是你想做动画的地方。

标签: react-native animation


【解决方案1】:

您可以像这样利用 JS Promise API:

const { Component } = require("react");
const { Animated } = require("react-native");

class SomeComponent extends Component {
    visibility = new Animated.Value(0);

    async componentDidMount() {
        // The code below will only run after `this.requestServerForData` has completed
        await this.requestServerForData();

        Animated.timing(this.visibility, {
            toValue: 1,
            duration: 800,
            delay: 800,
            useNativeDriver: false,
        }).start();
    }

    requestServerForData = async () => {
        // Do some asynchronous data fetching things
    };

    render() {
        // return ... your UI
    }
}

【讨论】:

    猜你喜欢
    • 2011-11-07
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 2018-02-20
    相关资源
    最近更新 更多