简体   繁体   English

为什么只有在首先检查某个方法之后才能调用该方法?

[英]Why am I only able to call a method after checking that it exists first?

In my render method, I can only render a random quote from fetched list of JSON quotes successfully if I check that the getter method used to get the quote (based on a random index) exists first. 在我的render方法中,如果我首先检查用于获取报价的getter方法(基于随机索引),则只能成功地从JSON报价的提取列表中渲染随机报价。 This works: {this.randomQuote ? this.randomQuote.quote : ''} 这有效: {this.randomQuote ? this.randomQuote.quote : ''} {this.randomQuote ? this.randomQuote.quote : ''} , but if I just do {this.randomQuote.quote} , I get "TypeError: Cannot read property 'quote' of undefined." {this.randomQuote ? this.randomQuote.quote : ''} ,但是如果我只做{this.randomQuote.quote}{this.randomQuote.quote}收到“ TypeError:无法读取未定义的属性'quote'”。 (Note that quote is the name of a property each object in an array of fetched JSON objects. So the randomQuote method selects an object from the JSON based on the random index that the randomQuoteIndex() method picks, but the quote property is selected only in the rendering.) How could it be that just checking to see if this.randomQuote isn't undefined first would enable me to call render this.randomQuote.quote ? (请注意,quote是获取的JSON对象数组中每个对象的属性的名称。因此randomQuote方法根据randomQuoteIndex()方法选择的随机索引从JSON中选择一个对象,但仅选择quote属性仅仅检查一下this.randomQuote是否未定义,怎么可能让我调用render this.randomQuote.quote

This is the working version of the class: 这是该类的工作版本:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      quotes: [],
      randomQuoteIndex: null
    }
  }

  componentDidMount() {
    // fetch method uses GET method by default; don't need to specify
    fetch('https://gist.githubusercontent.com/nataliecardot/0ca0878d2f0c4210e2ed87a5f6947ec7/raw/1802a693d02ea086817e46a42413c0df4c077e3b/quotes.json')
      // Takes a JSON response string and parses it into JS object
      .then(response => response.json())
      // state is set to quotes: quotes due to destructuring
      .then(quotes => this.setState({ quotes }, () => {
        this.setState({ randomQuoteIndex: this.randomQuoteIndex() })
      }));
  }

  get randomQuote() {
    return this.state.quotes[this.state.randomQuoteIndex];
  }

  randomQuoteIndex() {
    return random(0, this.state.quotes.length - 1);
  }

  render() {
    return (
      <div className="App" id="quote-box">
        {/* Since this is a get function, can call it as though it were a regular variable. Also, in this.random.quote, quote is the name of a property in each of the fetched JSON quote objects (that are held in an array) */}
        {this.randomQuote ? this.randomQuote.quote : ''}
        <Button
          buttonDisplayName="Next"
          clickHandler={this.buttonClickHandler}
        />
      </div>
    );
  }
}

Docs : 文件

The componentDidMount() method runs after the component output has been rendered to the DOM. 在将组件输出呈现到DOM之后, componentDidMount()方法将运行。

...so the first time it's rendered, this.state.randomQuoteIndex is null , this.state.quotes[null] is undefined , undefined.quote is bad. ...因此,第一次呈现时, this.state.randomQuoteIndexnullthis.state.quotes[null]undefinedundefined.quote不好。

If you put the check in, you survive the first render, and live to see the component when it's properly initialised. 如果签入,您将在第一个渲染中存活下来,并在正确初始化组件后看到组件。

Any time you have a component that may be caught naked and bashful, you want to make sure it can still render something correctly (and either hide, or display a spinner or something similar, till it's done dressing). 每当您有一个可能被裸露和害羞的组件时,您都想确保它仍然可以正确渲染某些东西 (并隐藏或显示微调器或类似的东西,直到完成修整为止)。 Ideally, it would be by having an explicit flag in its state saying "I'm decent now", not by checking a function that may return undefined due to a near-miss with a bug. 理想情况下,这将是通过在其状态下显示一个“我现在很不错”的显式标志,而不是通过检查可能由于错误导致的错误而返回undefined的函数。 :) :)

Your randomQuoteIndex function probably selects an index out of range, you should change it to: 您的randomQuoteIndex函数可能选择了超出范围的索引,您应该将其更改为:

randomQuoteIndex() {
  return Math.floor(Math.random() * this.state.quotes.length);
}

No need to use length -1, see https://www.w3schools.com/js/js_random.asp 无需使用长度-1,请参见https://www.w3schools.com/js/js_random.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我在原型中定义时无法调用函数? - why I am not able to call function while defining in prototype? 只有在第一个方法完成后才能调用另一个方法 - How to call another method only after first method is completly done 为什么我可以为只读属性分配值? - Why am I able to assign a value to a read only property? 为什么我只能在javascript中打印一个对象? - Why am I only able to print one object in javascript? 为什么我不能在NodeList上使用索引方法? - Why I am not able to use index method on NodeList? 为什么只返回第一个数组元素? - Why am I only getting the first array element returned? 我正在检查HTML表单中的字段是否为空,但只执行第一个&#39;if&#39;语句然后刷新页面 - I am checking if a field is empty in an HTML form, but only the first 'if' statement is executed and then it refreshes the page 即使满足所有条件,我也无法在使用过滤方法后设置属性值 - I am not able to set the value of property after using filter method even after all the conditions are satisfied 当我尝试调用我的方法时,为什么我会变得不确定? - Why am I getting undefined when I am trying to call my method? 为什么我无法使用JSON数据在JS函数调用上构建树 - Why I am not able to build tree on JS function call using JSON data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM