gpt4 book ai didi

javascript - this.setState 不是函数

转载 作者:可可西里 更新时间:2023-11-01 01:20:07 27 4
gpt4 key购买 nike

<分区>

我有以下组件,它维护在特定元素上触发事件时更新的状态,当更新状态时,它作为 Prop 传递给另一个组件。我目前正在尝试为什么我会收到以下错误“this.setState 不是函数”,它很可能没有绑定(bind)到正确的上下文。但我不确定这一点,我这样做对吗?

export default class SearchBox extends Component{

constructor(){
super()
console.log("search box imported");
this.state = {
results:[]
};
}

//this.setState({result: arrayExample})

searchGif(event) {
if(event.keyCode == 13){
let inputVal = this.refs.query.value;
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.giphy.com/v1/gifs/search?q='+inputVal+'&api_key=dc6zaTOxFJmzC', true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
// this.response = JSON.parse(xhr.responseText);
let returnedObj = JSON.parse(xhr.responseText);
//console.log(returnedObj.data);
let response = returnedObj.data.map(function(record){
let reformattedArray = { key: record.id,
id: record.id,
thumbnailUrl: record.images.fixed_height_small_still.url
};
return reformattedArray;
});
console.log(response);
this.setState({results: response});
}
}
xhr.send();
}
}


render(){

return(
<div>
<input className="search-input" ref="query" onKeyDown={this.searchGif.bind(this)} name="search" placeholder="Search"/>
<GifSwatch data={this.state.results} />
</div>
);
}
}

编辑:我刚刚意识到上下文在“onreadyStateChange”函数时发生了变化,所以我在 searchGif 中做了以下操作

searchGif(){
//other logic
var self = this;
xhr.onreadystatechange = function(){
//ajax logic
self.setState({results: repsonse});
}
}

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com