【问题标题】:How to return a value from an arrow function?如何从箭头函数返回值?
【发布时间】:2019-11-25 16:02:44
【问题描述】:

我正在尝试从这两个函数返回字符串并将其附加到我的对象参数中。 知道如何让它返回字符串吗?

 const getEmail = () => {
    ls.get('email').then((email) => {
        if (email == null) {
            return '';
        }
        return email;
    })
}

 const getPassword = () => {
    ls.get('password').then((password) => {
      if (password == null) {
            return '';
        }
        return password;
    })
}

const INITIAL_STATE = {
     email: getEmail(),
     password: getPassword(),
     user: null,
     error: '',
     loading: false
     };

【问题讨论】:

  • 你绝对不能从未来返回一个字符串,但你可以返回它的承诺。
  • 因此,您将无法将其分配到初始状态,但在 promise 解决时使用 setState 设置它

标签: javascript react-native arrow-functions


【解决方案1】:

你不能从未来返回字符串,但你可以返回承诺,将它存储在你的状态中,然后重用它!

class Example extends Component {
  state = {
    email: '';
  }

  getEmail = () => {
    ls.get('email').then((email) => {
      if (email == null) {
        this.setState({ email: ''});
      }
      this.setState({ email });
    })
  }

  render()...
}

【讨论】:

  • 你为什么同时使用await.then()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
相关资源
最近更新 更多