react-native-router-flux v4中onEnter属性未触发的问题排查
问题分析与修复方案
你遇到的核心问题是**onEnter属性的赋值方式错误**——你现在直接调用了isLoggedIn(userLoggedIn, hasUserInfo, hasSellerAccount),这会导致组件一渲染就立刻执行这个函数,而不是在导航进入该Scene的时候才触发。onEnter需要接收一个函数引用,而不是函数执行后的返回值(你的isLoggedIn没有返回值,所以实际传给onEnter的是undefined,自然不会在导航时触发)。
修复后的代码示例
我们可以直接把判断逻辑封装成一个函数,然后将函数引用传给onEnter:
const Auth = props => { const { component, key, userLoggedIn, hasUserInfo, hasSellerAccount} = props // 定义判断函数,不需要额外传参,直接使用组件props里的值 const handleEnter = () => { if(userLoggedIn && hasUserInfo && hasSellerAccount){ Actions.admin() } else if (userLoggedIn && !hasUserInfo){ Actions.userInformation() } else if (userLoggedIn && hasUserInfo && !hasSellerAccount){ Actions.createAccount() } else if (!userLoggedIn){ Actions.logIn() } } return( <Scene key={key} onEnter={handleEnter} // 直接传递函数引用,不调用 component={component} {...props} /> ) }
额外说明
如果你的userLoggedIn、hasUserInfo、hasSellerAccount是从Redux store映射过来的props,要确保这些状态更新时组件能重新渲染,这样handleEnter里的判断逻辑才会使用最新的状态值。
内容的提问来源于stack exchange,提问作者Daniel Naval
相关产品推荐
相关产品推荐

