在我的渲染方法中,如果我首先检查用于获取报价的 getter 方法(基于随机索引)是否存在,则只能成功地从获取的 JSON 报价列表中渲染随机报价。这有效:{this.randomQuote ? this.randomQuote.quote : ''}
,但如果我只是执行 {this.randomQuote.quote}
,我会得到“TypeError: Cannot read property 'quote' of undefined”。 (请注意,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>
);
}
}
最佳答案
Docs :
The
componentDidMount()
method runs after the component output has been rendered to the DOM.
...所以第一次渲染时,this.state.randomQuoteIndex
为null
,this.state.quotes[null]
是未定义
,undefined.quote
不好。
如果您进行了检查,您将在第一次渲染中幸存下来,并在正确初始化后看到组件。
任何时候你有一个组件可能会被抓到赤裸裸和害羞,你想要确保它仍然可以正确渲染某些东西(并且隐藏或显示旋转器或类似的东西,直到它是穿好衣服)。理想情况下,应该在其状态中设置一个显式标志,表示“我现在很体面”,而不是检查可能由于差点发生错误而返回 undefined
的函数。 :)
关于javascript - 为什么我只能在先检查方法是否存在后才能调用该方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56929710/