为什么下面这段代码的输出是“true”?
class InstagramGallery extends React.Component {
constructor(props) {
super(props);
this.state = {
images: true
};
}
componentDidMount() {
var accessToken = '*Instagram token*';
var instagramApi = new Instagram(accessToken);
instagramApi.userSelfMedia().then(function(result) {
this.setState({
images: false,
});
}, function(err) {
console.log(err);
});
}
render() {
console.log(this.state.images);
return (
<div className="instagram-gallery">
</div>
)
}
}
据我所知,首先调用构造函数。因此 images=true
,之后它使用 console.log(true)
渲染,并调用 componentDidMount
。从 instagram 获取数据后,我更新组件状态,它应该使用 images=false
重新渲染组件。我哪里错了?
最佳答案
您正在为 instagramAp.userSelfMedia
回调使用常规函数,因此丢失了 this
上下文。请改用箭头函数:
instagramApi.userSelfMedia().then(
result => {
this.setState({
images: false
});
},
function(err) {
console.log(err);
}
);
常规函数创建自己的词法范围,因此 this
不会在回调函数中指向您的类。箭头函数不会创建自己的词法范围,this
指向您的组件,您可以使用 this.setState()
。
使用箭头函数可以避免绑定(bind)函数或将 this
保存在另一个变量中,例如:
var accessToken = "*Instagram token*";
var instagramApi = new Instagram(accessToken);
const that = this;
instagramApi.userSelfMedia().then(
function(result) {
that.setState({
images: false
});
},
function(err) {
console.log(err);
}
);
关于javascript - React - 未设置组件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301264/