【问题标题】:React - async used with componentDidMount()React - 与 componentDidMount() 一起使用的异步
【发布时间】:2020-04-28 17:01:09
【问题描述】:

我正在处理 this 示例,希望能在理解以下代码部分的帮助下获得帮助。

 async componentDidMount() {
    const { match: { params } } = this.props;
    const question = (await axios.get(`http://localhost:8081/${params.questionId}`)).data;
    this.setState({
      question,
    });
  }
  1. 到目前为止,我还没有看到async 之前的字符串componentDidMount()。这能达到什么目的?我知道在页面的所有元素都正确呈现之后,这个方法被调用了,但是 async 在这里做什么?

  2. 请帮我了解const { match: { params } } = this.props;在这里做什么?

【问题讨论】:

  • 我觉得这是一种普遍的不良反应编码风格,因为 componentDidMount 属于反应生命周期。我会在组件内部调用一个单独的方法,它当然可以是异步的。但我个人会远离你的样本。

标签: reactjs


【解决方案1】:

1. 当您想在该函数中使用await 来等待异步调用返回时,您声明了一个函数async。我不认为你可以在componentDidMount 上使用async,但你可以使用promise:

componentDidMount() {
    const { match: { params } } = this.props;
    axios.get(`http://localhost:8081/${params.questionId}`)
         .then(res => {
             const question = res.data;
             this.setState({ question });
         });
}

2. 这叫做解构,意思是要从this.props中提取params

const { match: { params } } = this.props;

相当于:

const params = this.props.match.params

【讨论】:

    猜你喜欢
    • 2020-02-12
    • 2020-01-20
    • 2016-11-13
    • 2018-06-06
    • 1970-01-01
    • 2013-05-24
    • 2018-08-31
    • 1970-01-01
    • 2019-01-22
    相关资源
    最近更新 更多