我知道之前已经问过这个问题,但是我已经尝试了所有建议的解决方案,但没有一个能够工作(诚然,这可能归结为我是一个笨蛋) .

Anywho,我的特殊问题是以下行导致错误('TypeError:无法读取'undefined'的属性'setState'):this.setState({pictures:response,loading:false});

FWIW,前一行是一个console.log调用,告诉我响应已经回来了 .

这是完整的代码:

从'react-checkbox-group'中的'react'导入提取导入导入{checkbox,CheckboxGroup}导入;从'./Thumbs'导入Thumbs;

class Search extends Component {

constructor(props) {
    super(props)
    this.state = {
        loading: false,
        images: false,
        audio: false,
        pictures: []
    }
    this.handleSubmit = this.handleSubmit.bind(this);
}

componentWillUpdate(nextProps) {
    this.style = {backgroundColor: 'green'}
}

handleSubmit(e) {
    e.preventDefault();
    const search = e.target[0].value;
    const vid = e.target[1].checked;
    const aud = e.target[2].checked;

    var medium = "image";

    if (aud) {
        medium = "audio";
    }

    var endPoint = "https://images-api.nasa.gov/search?q=" + search + "&media_type=" + medium;
    console.log(endPoint);
    fetch(endPoint)
        .then(function(response) {
            if (response.status >= 400) {
                throw new Error("Bad response from server");
            }
            return response.json();
        })
        .then(function(response) {
            console.log(response);
            this.setState({pictures : response, loading: false});                //PROBLEM IS HERE
        });

}


render() {
    const { pictures, loading } = this.state
    function mediaChanged(newMedia) {
        if (newMedia.length === 2) {
            newMedia.shift();
        }
    };

    return (
        <div className="search">
            <h1>NASA Search</h1>
            <form onSubmit={this.handleSubmit}>
                <input type="search" width="60" placeholder="search term(s)"/>

<CheckboxGroup name="media" onChange={mediaChanged}> <label><Checkbox value="images"/> Images</label> <label><Checkbox value="audio"/> Audio</label> </CheckboxGroup> </form>





{(pictures.length) ? pictures.map( (pictures, i) => <Thumb key={i}/> ) : <span>-</span> } </div> ) }

}

导出默认搜索