在setTimeout之后,React-Native推送到其他路由

React-Native push to other route after a setTimeout

本文关键字:其他 路由 React-Native setTimeout 之后      更新时间:2023-09-26

我想知道是否可以使用setTimeout函数推送到另一条路由。我有一个组件谁是一个加载页面,我想做什么,如果在加载阶段完成后,我在屏幕上显示一个消息文本,但1秒后,我自动推到另一个路由。

我用的是react-native-router-flux

const pushRoute = () => setTimeout(() => Actions.home(), 1000);
const PhotoPageOnSave = ({ photoState: { message, loading, error } }) => {
  if (loading) {
    return (
      <Container>
        <View style={styles.root}>
          <Spinner size="large" color="white" />
        </View>
      </Container>
    );
  }
  return (
    <Container>
      <View style={[styles.root, error ? { backgroundColor: '#C70018' } : null]}>
        <View>
          <Text style={styles.textStyle}>{message}</Text>
        </View>
      </View>
      {() => pushRoute()}
    </Container>
  );
};

你想做的肯定是可能的。

{() => pushRoute()}

与…

{setTimeout(() => Actions.home(), 1000)}

{this.pushRoute}

? ?

我认为这是render()功能的一部分?

你可以这样做,只是在render()函数中通常不会这样做。通常这种行为是为componentDidMount()componentWillReceiveProps()保留的

类似:

componentWillReceiveProps(nextProps){
    if(!nextProps.loading){
        pushRoute();
    }
}

你可以在你的pushRoute函数中写一个承诺

 pushRoute(dly) {
    return new Promise(function(resolve, reject) {
      setTimeout(() => {
        resolve()
      }, dly);
    })
  }
并调用另一个必须是异步的函数例如onPress函数
async onPress(){
var result = await = this.pushRoute(1000);
// and now you are free to call navigator.psuh here after 1000ms.
}