重定向不适用于componentwillmount()反应 - 旋律频率


componentWillMount() {
    var user = UserService.findAll();
    if (user.length > 0) Actions.home();
  }

我的 router.js中的'home'是 Scene键。

另一方面

    onButtonPress() {
        var user = UserService.findAll();
        if (user.length > 0) Actions.home();
      }

像魅力一样工作!

我的router.js

const RouterComponent = () => {
  return (
    <Router showNavigationBar={false}>
      <Stack key="root">
        <Scene key="auth" hideNavBar={true}>
          <Scene key="login" component={Login} />
        </Scene>
        <Scene key="home" component={Home} hideNavBar={true}/>
        <Scene key="pdf" component={Pdf} hideNavBar={true} />
      </Stack>
    </Router>
  );
};
export default RouterComponent;

on props为我做到了

我需要有条件的导航,所以我使用了带有场景名称的successfailure属性来导航

我在下面发布我的代码,希望它能帮助某人

<Scene
    key="login"
    component={Login}
    on={() => UserService.findAll().length > 0}
    success={()=>
       Actions.replace("home")
    }  
    failure="login"
/>

好吧,我可以假设您试图在用户服务中获取或检查本地存储中的用户数据。我建议不要尝试使用生命周期钩componentWillMount阻止组件渲染或"安装"。相反,您可以在UserService.findAll()找到用户(由状态控制)时渲染ActivityIndicator,因为您不想在用户查找过程中完成userService之前的组件渲染。

类似的东西

在您的构造函数中,分配了一个值,该值将用于渲染ActivityIndicator或组件(我假设login组件)。让我们称其为 searching

// in your constructor
this.state = {
  searching : true;
}
// assuming it is an async function
async componentWillMount(){
  var user = await UserService.findAll();
  if (user.length > 0) {
    Actions.home({type : ActionConst.REPLACE}); // no need to update the state here as we will navigate to another screen resetting the navigation stack
  }else {
    this.setState({
      searching : false
    });
  }
}
// other methods etc
render(){
  return this.state.searching ? <ActivityIndicator /> : <Login />
}

当然,这是渲染方法的抽象

最新更新