javascript - 为什么我只能在先检查方法是否存在后才能调用该方法?

标签 javascript reactjs

在我的渲染方法中,如果我首先检查用于获取报价的 getter 方法(基于随机索引)是否存在,则只能成功地从获取的 JSON 报价列表中渲染随机报价。这有效:{this.randomQuote ? this.randomQuote.quote : ''},但如果我只是执行 {this.randomQuote.quote},我会得到“TypeError: Cannot read property 'quote' of undefined”。 (请注意,quote 是获取的 JSON 对象数组中每个对象的属性名称。因此 randomQuote 方法根据 randomQuoteIndex() 方法选择的随机索引从 JSON 中选择一个对象,但仅选择 quote 属性)为什么只要先检查 this.randomQuote 是否未定义就可以调用 render 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>
    );
  }
}

最佳答案

Docs :

The componentDidMount() method runs after the component output has been rendered to the DOM.

...所以第一次渲染时,this.state.randomQuoteIndexnullthis.state.quotes[null]未定义undefined.quote不好。

如果您进行了检查,您将在第一次渲染中幸存下来,并在正确初始化后看到组件。

任何时候你有一个组件可能会被抓到赤裸裸和害羞,你想要确保它仍然可以正确渲染某些东西(并且隐藏或显示旋转器或类似的东西,直到它是穿好衣服)。理想情况下,应该在其状态中设置一个显式标志,表示“我现在很体面”,而不是检查可能由于差点发生错误而返回 undefined 的函数。 :)

关于javascript - 为什么我只能在先检查方法是否存在后才能调用该方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56929710/

相关文章:

javascript - 如何正确处理axios错误以及如何获取详细的错误描述?

javascript - 如何选择数组的前三个元素并构造一个逗号分隔的字符串

php - 如何从客户端接收 json 对象到服务器的 php 二维数组中?

javascript - 使用ajax调用php函数时遇到问题

javascript - 当有多个组件时调用特定子 ref 的方法以使用react

javascript - 即使我已允许 https ://example. com/,来自源 'https://example.com' 的访问已被阻止

javascript - jQuery 和 Google URL Shortener API

javascript - Sinon - 监视构造函数方法

javascript - eslint:解析错误:导入期间出现意外 token

reactjs - Jest 意外标识符 : React