React Native:为什么对象分解在常规函数中不起作用?

时间:2019-03-01 00:08:18

标签: javascript function react-native object-destructuring

在将调用发送给我的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);
 }
}

1 个答案:

答案 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);
   }
  }
}