尝试使用 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>
);
} …Run Code Online (Sandbox Code Playgroud)