.bind(this)有时候不能在慢速设备上工作

时间:2016-12-26 01:44:22

标签: android reactjs react-native

我遇到了一个问题,有时候在较慢的设备上应用程序因绑定而崩溃(这个)不会将上下文绑定到类方法。例如:

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,但错误仍然存​​在。到目前为止我找到的唯一解决方案是将bind(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();
    }

}

或者简单地内联函数会避免这个错误,但是我仍然会对为什么会发生这种想法感到困惑,有什么想法吗?

由于

1 个答案:

答案 0 :(得分:2)

好吧,你绝不应该在.bind方法中使用render - 这确实会降低性能。

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

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

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

}

在您的情况下,您可以使用onPress={this.props.submit},因为您的_onPress方法根本不执行任何操作...

相关问题