【问题标题】:Why does asynchronous function cause PropTypes to be null为什么异步函数会导致 PropTypes 为空
【发布时间】:2021-06-11 12:30:42
【问题描述】:

我有一个带有这种结构的 Firebase 的简单反应应用

Project
 |    
 +-- src
 |  |  
 |  +-- component
             |
             +---SampleAppFolder
                      |
                      + index.js
                      + MySampleApp.js
 ...

index.js 中,我创建了一个React 组件 SampleAppPage,我尝试将道具从SampleAppPage 传递给MySampleApp,就像这样,

SampleAppPage extends React.Componet {

  render() {
    return (
    <MySampleApp varA={item.itemVarA} varB={item.itemData.itemVarB} varC={item.itemData.itemVarC || 0}/>
   )
  }
}

import React from 'react';
import PropTypes from 'prop-types';

class MySampleApp extends React.Component {

    static propTypes = {
        varA: PropTypes.number.isRequired,
        varB: PropTypes.string.isRequired,
        varC: PropTypes.string.isRequired,
    };

    constructor(props) {
        super(props);

        this.state = INITIAL_STATE;
        this.varA = db.getByReference(A_NODE);
        this.varB = db.getByReference(B_NODE);
        this.varC = db.getByReference(C_NODE);
    };

在调试模式下,props 可以正常传递,但在 MySampleApp 的渲染函数中,


<Button icon='like' floated='right' onClick={this.foo} loading={loading}/>

我像这样对 this.foo 函数变量进行了异步调用

foo = async () => {
      this.setState({ loading: true });

      try {
         console.log(this.props.varA); 
         console.log(this.props.varB);
         await db.pushToReference(); //asynchronous call to push data to Firebase Realtime database reference node

         this.setState({
             loading: false
         });
      }
      catch
      {


      }

}

为什么 varA 和 varB PropTypes 在 MySampleApp 构造函数中成功传递,但是当我调用异步函数时,为什么 varA 打印 而 var B 打印 null ?

是不是因为函数变量中的异步操作?

我是 JavaScript 领域的新手,所以请给我一些关于这个问题的见解?

【问题讨论】:

  • 当你传递 varB={item.itemData.itemVarB} 时,确保它有一个值,当你将它作为道具传递时,{item.itemData.itemVarB} 已经是 null

标签: javascript reactjs firebase-realtime-database


【解决方案1】:

您需要将this 绑定到 foo。因为它是一个匿名函数。

 constructor() {
    super();
    this.foo = this.foo.bind(this);
 } 

【讨论】:

  • 这对我有用,你能解释一下为什么this.props.varA 有效,但this.props.varBnull
  • 不确定,但您应该能够将整个项目作为道具传递给组件。而不是 3 个单独的道具。
猜你喜欢
  • 1970-01-01
  • 2019-10-05
  • 2019-11-14
  • 2012-04-20
  • 2012-04-24
  • 2018-05-31
  • 2013-04-03
  • 1970-01-01
  • 2011-05-10
相关资源
最近更新 更多