为什么这段代码的输出低于“真”?
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()
。
使用箭头功能可以避免绑定函数或将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);
}
);
我这么长时间没有使用RN,但这有影响吗?
componentDidMount() {
var accessToken = '*Instagram token*';
var instagramApi = new Instagram(accessToken);
instagramApi.userSelfMedia().then((result) => { //USING ARROW FUNCTION
this.setState({
images: false,
});
}, function(err) {
console.log(err);
});
}
我添加了一个箭头函数,以便'this.state'不会与instagramApi.userSelfMedia()中的'this'混淆。
因为这不可用
使用箭头功能
instagramApi.userSelfMedia().then((result) => {
this.setState({
images: false,
});
}, function(err) {
console.log(err);
});
}
或者手动绑定它
instagramApi.userSelfMedia().then(function(result) {
this.setState({
images: false,
});
}.bind(this), function(err) {
console.log(err);
});
}