How to set state , keep getting TypeError: Cannot read property 'setState' of undefined
How to set state , keep getting TypeError: Cannot read property 'setState' of undefined
我正在尝试使用从 axios 返回的数据设置状态 get.But 我一直收到此错误类型错误:无法读取未定义的 属性 'setState'。
class 页面扩展 React.Component {
constructor(props) {
super(props);
this.authenticated = props.authenticated;
//this.handleClick = this.handleClick.bind(this);
}
state ={
page : []
}
componentDidMount() {
let config = null;
//let token = null;
app.auth().currentUser.getIdToken(true).then(function(idToken) {
config = {
headers: {'Authorization': idToken}
};
console.log(config);
axios.get('http://localhost:4001/api/v1/page',config)
.then(res => {
console.log(res.data);
const page = res.data;
this.setState( page );
}).catch((err)=>{
console.log(err);
});
})
}
render () {
const authenticated = this.authenticated;
console.log(authenticated);
console.log(this.state);
return (
<h1> test 123</h1>
);
}
}
this inside axios指的是不同的东西,将this
的值存储在一个变量中并使用该变量
componentDidMount = () => {
let config = null;
//let token = null;
const current = this; // here save this in current variable
app
.auth()
.currentUser.getIdToken(true)
.then(function(idToken) {
config = {
headers: { Authorization: idToken }
};
console.log(config);
axios
.get('http://localhost:4001/api/v1/page', config)
.then(res => {
console.log(res.data);
const page = res.data;
current.setState(page); // use current here
})
.catch(err => {
console.log(err);
});
});
}
我正在尝试使用从 axios 返回的数据设置状态 get.But 我一直收到此错误类型错误:无法读取未定义的 属性 'setState'。
class 页面扩展 React.Component {
constructor(props) {
super(props);
this.authenticated = props.authenticated;
//this.handleClick = this.handleClick.bind(this);
}
state ={
page : []
}
componentDidMount() {
let config = null;
//let token = null;
app.auth().currentUser.getIdToken(true).then(function(idToken) {
config = {
headers: {'Authorization': idToken}
};
console.log(config);
axios.get('http://localhost:4001/api/v1/page',config)
.then(res => {
console.log(res.data);
const page = res.data;
this.setState( page );
}).catch((err)=>{
console.log(err);
});
})
}
render () {
const authenticated = this.authenticated;
console.log(authenticated);
console.log(this.state);
return (
<h1> test 123</h1>
);
}
}
this inside axios指的是不同的东西,将this
的值存储在一个变量中并使用该变量
componentDidMount = () => {
let config = null;
//let token = null;
const current = this; // here save this in current variable
app
.auth()
.currentUser.getIdToken(true)
.then(function(idToken) {
config = {
headers: { Authorization: idToken }
};
console.log(config);
axios
.get('http://localhost:4001/api/v1/page', config)
.then(res => {
console.log(res.data);
const page = res.data;
current.setState(page); // use current here
})
.catch(err => {
console.log(err);
});
});
}