我希望在解析承诺后修改组件的状态(本机反应)。
这是我的代码:
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>
);
}
}
但是当承诺解决时,它会抛出以下错误:
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)
如何在解析承诺后更改当前的组件状态?
答案 0 :(得分:6)
回调具有与您正在使用的对象不同的上下文。因此,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));
}
答案 1 :(得分:1)
使用新语法会更好。更多https://babeljs.io/blog/2015/06/07/react-on-es6-plus
class Greeting extends Component{
state = {
text: 'Starting...',
}
componentDidMount() {
var handler = new RequestHandler();
handler.login('email','password')
.then((text) => {
this.setState({ text });
})
}
render(){
return (
<Text style={this.props.style}>
Resp: {this.state.text}
</Text>
);
}
}