React代码执行优先级问题:this.props.navigation未定义
解决React组件自定义方法中
this.props未定义的问题 嘿,我来帮你搞定这个问题!你遇到的核心原因是:类组件里的普通函数不会自动绑定组件实例的this,所以在Nauthedcard()方法里,this并没有指向当前的组件实例,自然就访问不到this.props了。
下面给你三种常用的解决办法,任选其一都能解决问题:
方法一:用箭头函数定义自定义方法
箭头函数会自动捕获当前上下文的this,直接把Nauthedcard改成箭头函数形式就行,这样this就会指向组件实例,能正常访问this.props了:
class YourComponent extends React.Component { constructor(props) { super(props); this.authed = this.props.navigation.getParam('authed', ''); } // 箭头函数自动绑定this Nauthedcard = () => { console.log(this.props.navigation); // 现在能正常输出了 return( <Button onPress={() => this.props.navigation.navigate('Home')} rounded small iconRight> <Text> Login </Text> <Icon type="FontAwesome" name="sign-in" /> </Button> ); } render() { return ( <>{ this.authed === '' && this.Nauthedcard() }</> ); } }
方法二:在构造函数里手动绑定this
如果你习惯用普通函数定义方法,可以在构造函数里手动把Nauthedcard的this绑定到组件实例:
class YourComponent extends React.Component { constructor(props) { super(props); this.authed = this.props.navigation.getParam('authed', ''); // 手动绑定this到组件实例 this.Nauthedcard = this.Nauthedcard.bind(this); } Nauthedcard() { console.log(this.props.navigation); // 正常输出 return( <Button onPress={() => this.props.navigation.navigate('Home')} rounded small iconRight> <Text> Login </Text> <Icon type="FontAwesome" name="sign-in" /> </Button> ); } render() { return ( <>{ this.authed === '' && this.Nauthedcard() }</> ); } }
方法三:调用方法时临时绑定this
也可以在render里调用Nauthedcard的时候,用bind或者箭头函数包裹来绑定this:
render() { return ( // 用bind绑定this <>{ this.authed === '' && this.Nauthedcard.bind(this)() }</> // 或者用箭头函数包裹 // <>{ this.authed === '' && (() => this.Nauthedcard())() }</> ); }
不过这种方式有个小局限:每次组件render都会创建新的函数实例,在复杂组件里可能带来轻微的性能损耗(一般场景下可以忽略),所以更推荐前两种方法。
小优化建议
另外,你在render里的判断条件可以改成this.authed === ''(严格相等),比==更严谨;如果authed可能是null或者undefined,也可以用!this.authed来判断,覆盖更多空值场景。
内容的提问来源于stack exchange,提问作者27mdmo7sn
相关产品推荐
相关产品推荐

