【问题标题】:arguments object is of zero length even after I can access its propertiesarguments 对象的长度为零,即使我可以访问它的属性
【发布时间】:2020-04-09 12:46:28
【问题描述】:

为什么当我将参数传递给函数时,甚至当我可以访问它的属性时,参数对象的长度为零? 我说的是所有 javascript 函数都实现的 arguments 对象,您可以从中访问函数参数。您可以在这里了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

发生的情况是,当我将 arguments 对象的长度打印到控制台时,它说它有 cero 长度,但是当我从我的函数(组件)内部访问它时,我仍然可以使用它的一个属性。您可以阅读下面代码中的 cmets 了解更多详细信息。

我正在使用对打字稿做出反应。

interface Props{
id: string;
className?: string;    
}

export const Buttons: React.FC<Props> = function(){


  function arg(){

    console.log("Funciona");
    console.log("arguments object: "+arguments);
    {/*This prints to the console that the arguments objects is of cero (0) length*/}
    {/*Even when is posible to access
    the id property that I have passed from App component*/}
    console.log("arguments object: "+arguments.length);
    console.log("arguments object: "+arguments[0]);

    for(let i=0; i < arguments.length; i++){

      {/*It will never enter the for loop*/}

      console.log("arguments object: "+arguments[i]);

    }

  }{/*end arg*/}

  React.useEffect(

    ()=>{

      window.setTimeout(arg, 5000);

    },
    []

  );

  return(

    {/*This will work as I'm  able to see the id from the dev tools*/}
    <section id={arguments[0].id}>{}

      <div className="container">

        <p>Hello World</p>

      </div>

    </section>

  );
} 

这里我传递了 id 属性:

const App: React.FC = () => {
  return (

    <div className="App">

      <Buttons id="buttons" />

    </div>

  );
}

【问题讨论】:

  • 不要在您的帖子中添加垃圾文本来绕过要求您解释更多问题的要求 - 相反,请更详细地解释问题,例如作为您尝试过的哪种调试不起作用。查找如何创建 minimal reproducible example 也可能会有所帮助 - 考虑删除与问题不直接相关的代码。
  • @CertainPerformance 所有代码都与问题相关,但是是的,我将添加更多细节,因为我意识到问题尚不清楚。

标签: javascript reactjs typescript


【解决方案1】:

我不确定你的问题是否理解?

您是否尝试通过执行 arguments[0].id 来访问 id props

您可以通过以下方式访问组件的“参数”(在 react 中称为 props):

替换:

export const Buttons: React.FC<Props> = function(){

作者:

export const Buttons: React.FC<Props> = function(props){

然后打电话

props.id

祝你好运

【讨论】:

  • 是的,但这是正常行为。您返回的“参数” var 与您的 arg() 函数中的不同。范围不一样。在您的组件中,它采用“props”参数。在您的 arg() 函数中。它采用 arg() 参数,该参数为空。请在您的 arg() 函数中,使用“this.props”访问与组件参数相同的参数
  • 它抛出此错误“'this' 隐含类型'any',因为它没有类型注释。TS2683”我也尝试了 this.arguments 没有 props 关键字。我希望能够访问组件的参数对象,而无需将道具传递给我的组件,就像我从 return 语句访问它一样。
  • 我没有注意到它是一个功能组件,对不起,我的错误。我刚刚更新了我的答案,以便您可以正确参考。
猜你喜欢
  • 2015-12-30
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
相关资源
最近更新 更多