React native 重定向在componentWillMount()上不起作用
其中“home”是myReact native 重定向在componentWillMount()上不起作用,react-native,react-navigation,react-native-router-flux,React Native,React Navigation,React Native Router Flux,其中“home”是myrouter.js中的场景键 另一方面 componentWillMount() { var user = UserService.findAll(); if (user.length > 0) Actions.home(); } 工作得很有魅力 我的router.js onButtonPress() { var user = UserService.findAll(); if (user.length &
router.js中的场景
键
另一方面
componentWillMount() {
var user = UserService.findAll();
if (user.length > 0) Actions.home();
}
工作得很有魅力
我的router.js
onButtonPress() {
var user = UserService.findAll();
if (user.length > 0) Actions.home();
}
constroutercomponent=()=>{
返回(
);
};
导出默认路由组件;
好的,我可以假设您正在尝试获取或检查本地存储中的用户服务中的用户数据。我建议不要尝试使用lifecycle钩子阻止组件呈现或“装载”componentWillMount
。相反,您可以在UserService.findAll()
查找用户(由状态控制)时呈现ActivityIndicator
,因为在完成UserService的用户查找过程之前,您不希望呈现组件
诸如此类
在构造函数中,指定一个值,该值将用于呈现ActivityIndicator
或组件(我假设login
组件)。让我们称之为搜索
,例如:
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;
//在构造函数中
此.state={
搜索:正确;
}
//假设它是一个异步函数
异步组件willmount(){
var user=await UserService.findAll();
如果(user.length>0){
Actions.home({type:ActionConst.REPLACE});//无需在此处更新状态,因为我们将导航到另一个屏幕,重置导航堆栈
}否则{
这是我的国家({
搜索:false
});
}
}
//其他方法等
render(){
是否返回此.state.search?:
}
当然,这是渲染方法的一个抽象,但您可以理解要点:)上的道具为我做了这个把戏
我需要有条件的导航,所以我使用了带有场景名称的success
和failure
属性来导航
我在下面发布我的代码,希望它能帮助别人
// 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 />
}
UserService.findAll().length>0}
成功={()=>
行动。替换(“主页”)
}
failure=“登录”
/>
当组件将挂载时,您是否收到任何错误消息?没有错误,我尝试了超时,但它工作正常,但这不是我不想做的,因为它使屏幕能够提供帮助。如果您能解释您的流程,那就太好了。如果这是应用程序(启动)的开始,并且用户登录时被引导到主页,或者需要登录时进行身份验证,那么我建议将主页组件之外的逻辑移动到启动屏幕中,以便在应用程序初始化时进行检查,并将用户引导到正确的场景。我仅在启动屏幕上执行此操作。。。我的意思是我没有任何闪屏。我要么登录,要么回家。总之,这里的启动屏幕是登录屏幕谢谢您的回答,但是Userservice.findAll()并没有占用任何时间。它的同步方法。当我将调试器放在这一行时:if(user.length>0)Actions.home()代码>我得到操作
未定义@Mohammad Abbas,我会尝试你的代码并更新你好的,让我知道你是如何使用它的:)不,它不起作用:(无论如何,非常感谢你的帮助
<Scene
key="login"
component={Login}
on={() => UserService.findAll().length > 0}
success={()=>
Actions.replace("home")
}
failure="login"
/>