.bind(this)有时无法在缓慢的设备上工作

问题描述:

我遇到了一个问题,有时在较慢的设备上,应用程序因绑定而崩溃(此操作)不会将上下文绑定到类方法。例如:.bind(this)有时无法在缓慢的设备上工作

class mycomp extends Component { 


    render() { 
     return <TouchableOpacity onPress={this._onPress.bind(this)}/>; 
    } 

    _onPress() { 
     let {submit} = this.props; // <-- here throws error 
     submit(); 
    } 

} 

它说undefined is not an object {evaluating this.props.submit},这只发生在某些设备上。也试过autobind并且错误仍然发生。到目前为止,我已经找到了唯一的解决办法是移动绑定(this)来构造:

class mycomp extends Component { 

    constructor(props) { 
     super(props); 
     // move `bind` statement here 
     this._onPress = this._onPress.bind(this); 
    } 

    render() { 
     return <TouchableOpacity onPress={this._onPress}/>; 
    } 

    _onPress() { 
     let {submit} = this.props; 
     submit(); 
    } 

} 

或者干脆内联函数会避免这个错误,但我仍然困惑,为什么这会发生什么,任何想法?

感谢

嘛,你不应该使用.bindrender方法 - 它确实会降低性能。

相反,使用类属性(方法用箭头函数定义)来绑定上下文。

class Mycomp extends Component { 
    _onPress =() => { 
     let {submit} = this.props; // <-- here throws error 
     submit(); 
    } 

    render() { 
     return <TouchableOpacity onPress={this._onPress}/>; 
    } 

} 

在你的情况,你可以使用onPress={this.props.submit},因为你的_onPress方法做什么都没有......

+0

它的伟大工程!谢谢 ! – Xeijp