在promise解析后修改组件状态

leo*_*o7r 6 javascript react-native

我希望在解析promise之后修改组件的状态(本机反应).

这是我的代码:

    class Greeting extends Component{

    constructor(props){
        super(props);

        this.state = {text: 'Starting...'};

        var handler = new RequestHandler();
        handler.login('email','password')
        .then(function(resp){
            this.setState({text:resp});
        });
    }

    render(){
        return (
            <Text style={this.props.style}>
                Resp: {this.state.text}
            </Text>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当promise解决时,它会抛出以下错误:

this.setState is not a function
TypeError: this.setState is not a function
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:1510:6
    at tryCallOne (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25187:8)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25273:9
    at JSTimersExecution.callbacks.(anonymous function) (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:8848:13)
    at Object.callTimer (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:8487:1)
    at Object.callImmediatesPass (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:8586:19)
    at Object.callImmediates (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:8601:25)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7395:43
    at guard (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7288:1)
    at MessageQueue.__callImmediates (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7395:1)
Run Code Online (Sandbox Code Playgroud)

在解决了承诺后,如何更改当前的组件状态?

Tim*_*imo 7

回调具有与您正在使用的对象不同的上下文.出于这个原因,this不是你认为的那样.


要解决此问题,您可以使用箭头函数,它保留周围的上下文:

constructor(props){
    super(props);

    this.state = {text: 'Starting...'};

    var handler = new RequestHandler();
    handler.login('email','password')
        .then(resp => this.setState({text:resp}));
}
Run Code Online (Sandbox Code Playgroud)

或者,使用bind()以下方法手动设置函数上下文

constructor(props){
    super(props);

    this.state = {text: 'Starting...'};

    var handler = new RequestHandler();
    handler.login('email','password')
        .then(function(resp){
            this.setState({text:resp});
        }.bind(this));
}
Run Code Online (Sandbox Code Playgroud)