[英]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.