在将调用发送给我的REST API之前,使用对象分解来破坏我的状态,并且它仅对我有用。我尝试在常规函数内部调用它,但不断收到错误消息,提示它未定义。代码示例如下
我正在子组件中调用该函数,我不确定这是否有所不同。非常感谢您的帮助,我可以学习这个概念,谢谢!
代码我不明白为什么会破坏
async get() {
const { userData } = this.state
try {
const response = await http.get('/v1', {
userData
})
console.log('response', response);
await this.setState({friends: response.data});
} catch(err) {
console.log("error getting friends ", err);
}
}
**有效的代码**
get = async () => {
const { userData } = this.state
try {
const response = await http.get('/v1', {
userData
})
console.log('response', response);
await this.setState({friends: response.data});
} catch(err) {
console.log("error getting friends ", err);
}
}
答案 0 :(得分:0)
我认为您的代码由于this
关键字而无法正常工作。 Understanding this keyword in javascript
使其起作用。您可以将方法绑定到类的构造函数中。例如。
class Example {
constructor(){
// ...
this.get = this.get.bind(this); // Or bind the method that you call get method
}
async get() {
const { userData } = this.state
try {
const response = await http.get('/v1', {
userData
})
console.log('response', response);
await this.setState({friends: response.data});
} catch(err) {
console.log("error getting friends ", err);
}
}
}