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

时间:2019-07-08 06:53:27

标签: javascript reactjs

在我的render方法中,如果我首先检查用于获取报价的getter方法(基于随机索引),则只能成功地从JSON报价的获取列表中渲染随机报价。这有效:{this.randomQuote ? this.randomQuote.quote : ''},但是如果我只是做{this.randomQuote.quote},则会收到“ TypeError:无法读取未定义的属性'quote'”。 (请注意,quote是获取的JSON对象数组中每个对象的属性名称。因此,randomQuote方法根据randomQuoteIndex()方法选择的随机索引从JSON中选择一个对象,但仅选择quote属性

>如何先检查this.randomQuote是否未定义才可以使我调用渲染this.randomQuote.quote

这是该类的有效版本:

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>
    );
  }
}

2 个答案:

答案 0 :(得分:5)

Docs

  

componentDidMount()方法在组件输出呈现到DOM之后运行。

...因此,第一次渲染时,this.state.randomQuoteIndexnullthis.state.quotes[null]undefinedundefined.quote不好。

如果签入,您将在第一个渲染中幸存下来,并在正确初始化组件后实时查看。

每当您有一个可能被裸露和害羞的组件时,您都想确保它仍然可以正确渲染 (并隐藏或显示微调器或类似的东西,直到它被做完了)。理想情况下,这将是通过在其状态下显示一个“我现在很不错”的显式标志,而不是通过检查可能由于错误导致的错误而返回undefined的函数。 :)

答案 1 :(得分:0)

您的randomQuoteIndex函数可能选择了超出范围的索引,您应该将其更改为:

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

无需使用长度-1,请参见https://www.w3schools.com/js/js_random.asp

相关问题