首页 > 解决方案 > ReactJs 应用程序因错误“考虑将错误边界添加到您的树”而崩溃

问题描述

尝试使用 React 构建随机报价 api 应用程序。当第一次在 Button Click 上加载应用程序时,它会生成随机报价。但是在第二次单击应用程序崩溃时出现“应用程序组件中发生错误”“考虑向树中添加错误边界以自​​定义错误处理行为。

class App extends React.Component {
  state = {
    quotes: null
  };
  componentDidMount() {
  fetch("https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json")
      .then(res => res.json())
      .then(data => {
        // console.log(data);
        this.setState({
          quotes: data.quotes
        });
      });
    // console.log(this.state.quotes);
  }
  randomQuoteHandler = () => {
    const randNumb = Math.floor(Math.random() * this.state.quotes.length);
    const randomQuote = this.state.quotes[randNumb];
    this.setState({
      quotes: randomQuote
    });
    console.log(this.state.quotes);
  };
  render() {
    return (
      <div>
        <button onClick={this.randomQuoteHandler}>gen</button>
        <p>{this.state.quotes !== null && this.state.quotes.quote}</p>
        <p> {this.state.quotes !== null && this.state.quotes.author}</p>
      </div>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

标签: javascriptreactjsfetch

解决方案


将数组randomQuoteHandler替换this.state.quotes为选定quote的对象。所以在第二次点击时,this.state.quotes.length是未定义的。

您需要将所选报价存储在另一个状态变量中,例如randomQuote.

class App extends React.Component {
  state = {
    quotes: null,
    randomQuote: null,
  }
  componentDidMount() {
    fetch(
      'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json',
    )
      .then(res => res.json())
      .then(data => {
        // console.log(data);
        this.setState({
          quotes: data.quotes,
        })
      })
    // console.log(this.state.quotes);
  }
  randomQuoteHandler = () => {
    const randNumb = Math.floor(Math.random() * this.state.quotes.length)
    const randomQuote = this.state.quotes[randNumb]
    this.setState({
      randomQuote: randomQuote,
    })
    console.log(this.state.quotes)
  }
  render() {
    return (
      <div>
        <button onClick={this.randomQuoteHandler}>gen</button>
        <p>{this.state.randomQuote !== null && this.state.randomQuote.quote}</p>
        <p>{this.state.randomQuote !== null && this.state.randomQuote.author}</p>
      </div>
    )
  }
}

推荐阅读