无法读取未定义的属性“ setState”

0 javascript babel ecmascript-6 reactjs webpack

import React,{Component} from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import videoDetails from './components/listvideos';

class YoutubeApp extends Component {
    constructor(props){
        super(props)

    this.state = {
          videos:[]
    };

    this.apiCall('surfing');
    
   
}
    apiCall(term){
        const params = {
            part: 'snippet',
            key:APP_KEY,
            q:term,
            type: 'video'
        };
    axios.get(APP_URL, { params: params})
        .then(function(response) {
           this.setState({
               videos:response
           })
        })
        .catch(function(error) {
        console.error(error);
      });
   }

    render(){
        
        return (
            <div>
            <videoDetails/>
            </div>
        )
    }


}


ReactDOM.render(
    <YoutubeApp/>,
    document.getElementById('app')
)
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app">
</div>
Run Code Online (Sandbox Code Playgroud)

嗨,我正在尝试制作youtube克隆作为练习,我是一个初学者,但是我看不到为什么反应状态会给我一个问题,我正在尝试将状态设置为我的视频数组,以便可以将其传递给其他组件我没有包含api密钥或url,但是通过错误{无法读取未定义的属性'setState'}的方式非常可读

Bar*_*uch 5

function()在Promise链中使用,这将更改的范围this。如果您使用的是ES6,建议您使用arrow函数维护类范围。例:

您正在使用

axios.get(APP_URL, { params: params})
    .then(function(response) { // this resets the scope
       this.setState({
           videos:response
       })
    })
Run Code Online (Sandbox Code Playgroud)

尝试使用箭头功能:

axios.get(APP_URL, { params: params})
    .then((response) => {
       this.setState({
           videos:response
       })
    })
Run Code Online (Sandbox Code Playgroud)