javascript - 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>
解决方案
将数组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>
)
}
}
推荐阅读
- listview - Xamarin.Forms - ListView 加载/填充后如何滚动到底部?
- amazon-web-services - 使用 gitlab CI 通过 CLI 创建 lambda 函数时出错(解析参数“--zip-file”时出错:无法加载参数文件)
- wordpress - 如何在 WooCommerce REST API(related_ids) 中获取相关产品?
- cypress - “.to.be.sorted()”断言不适用于赛普拉斯
- android - Android可点击跨度点击激活所有TextView不仅可跨文本
- assembly - 在制作 PIE 对象时,不能使用针对未定义符号“ELF”的重定位 R_X86_64_8
- docker - 如何修复 minikube - skaffold 本地环境的服务端口?
- java - QueryDSL 为子查询重用表别名
- python - 如何使用python在opencv中加载图像?
- python - 从教程编写应用程序时出错