首页 > 解决方案 > setInterval 方法有什么问题?

问题描述

我正在设计一个移动应用程序中的屏幕,它应该会自动消失并导航到下一个屏幕。为此,我在以下代码中使用 setInterval :

componentDidMount(){
      Animated.timing(this.state.AnimVal, {
          toValue: 1,
          duration: 500 ,
          delay: 1000,
          useNativeDriver: true,
      }).start();

      var timer = setInterval( () => {
        this.setState({
          isLoaded: true,
        });
      }, 1000);
      if(this.state.isLoaded){
        this.props.navigation.navigate({ routeName: 'Guideline'})
      };
  };

isLoaded 状态变量方法应该变为真,因此,屏幕必须消失。但它没有发生,屏幕仍然存在。知道有什么问题吗?

标签: react-native

解决方案


这是因为当 setInterval 调用 setState 时,它​​会重新渲染组件,但它们并没有调用 componentDidMout。 在此处输入图像描述

对于本机反应> 0.6:

static getDerivedStateFromProps(props, state){
if(state.isLoaded){
        //here may be has problem
        props.navigation.navigate({ routeName: 'Guideline'})
   };
}

对于 react-native < 0.6:

componentWillReceiveProps(nextprops){
if(this.state.isLoaded){
        this.props.navigation.navigate({ routeName: 'Guideline'})
      };
}

我建议它根据您的情况使用 componentDidUpdate。因为 getDerivedStateFromProps 是静态的。它不能调用 this.props.navigation

componentDidUpdate(prevProps, prevState, snapshot) {
   if(this.state.isLoaded){
        this.props.navigation.navigate({ routeName: 'Guideline'})
      };
  }

推荐阅读