相关疑难解决方法(0)

this.setState不是函数

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

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(); …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 reactjs

17
推荐指数
1
解决办法
4万
查看次数

标签 统计

ecmascript-6 ×1

javascript ×1

reactjs ×1