解决 promise 后,我想修改组件的状态( native react )。
这是我的代码:
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>
);
}
}
但是,当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)
兑现 promise 后,如何更改当前的组件状态?
最佳答案
回调的上下文与您使用的对象的上下文不同。因此,this
不是您认为的那样。
为了解决这个问题,您可以使用arrow function,它保留了周围的上下文:
constructor(props){
super(props);
this.state = {text: 'Starting...'};
var handler = new RequestHandler();
handler.login('email','password')
.then(resp => this.setState({text:resp}));
}
或者,使用
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));
}
关于javascript - promise 解决后修改组件状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39152959/