如何在反应导航中设置计时器?

时间:2019-07-12 15:08:36

标签: react-native react-navigation react-native-navigation

我尝试用计时器导航react-native-navigation。因此,如果计时器的值为“ 5”,则将调用导航到“主页”。

我使用三元操作来调用导航。

import React from 'react';
import {
  View,
  Text,
  Button
} from 'react-native';
import {styles} from './AppStyle'
import {createStackNavigator, createAppContainer} from 'react-navigation'
import HomeScreen from './Pages/Home'

class Timer extends React.Component{
  constructor(props){
    super(props)
      this.state = {
        time : props.count
    }
  }

  componentDidMount(){
    this.addInterval = setInterval( () => this.increase(), 1000)
  }

  componentWillUnmount(){
    clearInterval(this.addInterval)
  }

  increase(){
    this.setState((_state, _props) => ({
      time: parseInt(this.state.time) + 1
    }))
  }

  render(){
    return(
      <Text> {this.state.time} </Text>
    );
  }

}
class StartScreen extends React.Component {
  render(){
    return (
      <View style={styles.container}>
        <View style={styles.navbar}>
          <Timer count='0'/>
          {this.props.count == '5' ? ()=>this.props.navigation.navigate('Home') : ''}
        </View>
      </View>
    );
  };
}

const HomeNavigator = createStackNavigator(
  {
    Home: {
      screen: HomeScreen
    }
  }
)

const StartNavigator = createStackNavigator(
  {
    Start: {
      screen: StartScreen
    },
    Main: {
      screen: HomeNavigator
    }    
  },
  {
    mode: 'modal',
    headerMode: 'none'
  },
  {
    initialRouteName: 'Start'
  }
)

const AppContainer = createAppContainer(StartNavigator);

export default class App extends React.Component {
  render() {
    return <AppContainer/>
  }
}

我希望当计数为“ 5”时,屏幕将导航至“主页”,但是我遇到了以下问题:“不变违反:不变违反:文本字符串必须在组件内呈现”

2 个答案:

答案 0 :(得分:0)

为您的onIncrease组件创建一个Timer道具,而不是直接在render中进行函数调用。

class Timer extends React.Component {
  /* component functions */

  increase = () => {
    const { time } = this.state
    const { onIncrease } = this.props
    const newTime = time + 1
    onIncrease(newTime)
    this.setState({ time: newTime })
  }

  /* render function */
}

class StartScreen extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.navbar}>
          <Timer
            count={0}
            onIncrease={count => {
              if (count === 5) {
                this.props.navigation.navigate('Home')
              }
            }}
          />
        </View>
      </View>
    )
  }
}

答案 1 :(得分:0)

您也可以使用setTimeout代替:

{this.props.count == '5' ? ()=>this.props.navigation.navigate('Home') : ''}

可以做到

{ setTimeout(()=>{ this.props.navigation.navigate("Home") }, 3000);}