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')
)
<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>
嗨,我正在尝试制作一个 YouTube 克隆来进行练习,我是这方面的初学者,但我不明白为什么 React 的状态给我带来了问题 我正在尝试将状态设置为我的视频数组,以便我可以将其传递给其他组件,我没有包含 api key 或 url,但这是非常可读的,这是错误 {无法读取未定义的属性“setState”}
最佳答案
您在 Promise 链中使用 function()
,这将更改 this
的范围。如果您使用 ES6,我建议您使用箭头函数来维护类范围。示例:
您正在使用
axios.get(APP_URL, { params: params})
.then(function(response) { // this resets the scope
this.setState({
videos:response
})
})
尝试使用箭头函数:
axios.get(APP_URL, { params: params})
.then((response) => {
this.setState({
videos:response
})
})
关于javascript - 无法读取未定义的属性 'setState',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45598011/