[英]Why am I only able to call a method after checking that it exists first?
在我的render方法中,如果我首先检查用于获取报价的getter方法(基于随机索引),则只能成功地从JSON报价的提取列表中渲染随机报价。 这有效: {this.randomQuote ? this.randomQuote.quote : ''}
{this.randomQuote ? this.randomQuote.quote : ''}
,但是如果我只做{this.randomQuote.quote}
, {this.randomQuote.quote}
收到“ TypeError:无法读取未定义的属性'quote'”。 (请注意,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>
);
}
}
文件 :
在将组件输出呈现到DOM之后,
componentDidMount()
方法将运行。
...因此,第一次呈现时, this.state.randomQuoteIndex
为null
, this.state.quotes[null]
是undefined
, undefined.quote
不好。
如果签入,您将在第一个渲染中存活下来,并在正确初始化组件后看到组件。
每当您有一个可能被裸露和害羞的组件时,您都想确保它仍然可以正确渲染某些东西 (并隐藏或显示微调器或类似的东西,直到完成修整为止)。 理想情况下,这将是通过在其状态下显示一个“我现在很不错”的显式标志,而不是通过检查可能由于错误导致的错误而返回undefined
的函数。 :)
您的randomQuoteIndex函数可能选择了超出范围的索引,您应该将其更改为:
randomQuoteIndex() {
return Math.floor(Math.random() * this.state.quotes.length);
}
无需使用长度-1,请参见https://www.w3schools.com/js/js_random.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.