无法读取未定义的属性“ setState” [英] Cannot read property 'setState' of undefined
问题描述
从'react'导入React,{Component};从'react-dom'导入ReactDOM;从'axios'导入axios;从'./components/listvideos';中导入videoDetails;类YoutubeApp扩展了Component {构造器(props){super(props)this.state = {videos:[]}; this.apiCall('surfing'); } apiCall(term){const params = {部分:代码段,键:APP_KEY,q:项,类型:视频}; axios.get(APP_URL,{params:params}).then(function(response){this.setState({video: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克隆作为练习,我是对此的初学者,但我看不到为什么反应状态会给我一个问题
我正在尝试将状态设置为我的视频数组,以便可以将其传递给其他组件,但我不包括api密钥或url,但是通过错误
的方式可读性很强{无法读取属性'setState 'of undefined}
您正在使用 Promise链中的> function()
,这将更改 this
的范围。如果您使用的是ES6,建议您使用箭头功能维护类范围。示例:
您正在使用
axios.get(APP_URL ,{params:params})
.then(function(response){//这会重置范围
this.setState({
videos:response
})
})
尝试使用箭头功能:
axios.get(APP_URL,{params:params})
.then((response)=> {
this.setState({
视频:响应
})
})
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>
Hi I am trying to make a youtube clone for practice I am a beginner on this but i cannot see why the state on react is giving me a problem I am trying to set the state to my videos array so i can pass it to other components I didn't include the api key or url but is very readable by the way this is the error {Cannot read property 'setState' of undefined}
You're using function()
in your Promise chain, this will change the scope for this
. If you're using ES6 I suggest you use the arrow function to maintain the class scope. Example:
You're using
axios.get(APP_URL, { params: params})
.then(function(response) { // this resets the scope
this.setState({
videos:response
})
})
Try using arrow functions:
axios.get(APP_URL, { params: params})
.then((response) => {
this.setState({
videos:response
})
})
这篇关于无法读取未定义的属性“ setState”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!