Nat*_*lie 0 javascript reactjs
在我的render方法中,如果我首先检查用于获取报价的getter方法(基于随机索引),则只能成功地从JSON报价的提取列表中渲染随机报价。这可以正常工作:{this.randomQuote ? 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
文件:
该
componentDidMount()
方法在组件输出呈现到DOM之后运行。
...所以它第一次被渲染this.state.randomQuoteIndex
是null
,this.state.quotes[null]
是undefined
,undefined.quote
是不好的。
如果签入,您将在第一个渲染中幸存下来,并在正确初始化组件后看到组件。
每当您有一个可能被裸露和害羞的组件时,您都想确保它仍然可以正确渲染某些东西(并隐藏或显示微调器或类似的东西,直到完成修整为止)。理想情况下,这将是通过在其状态下显示一个“我现在很体面”的显式标志,而不是通过检查可能undefined
由于错误导致的错误而返回的函数。:)
归档时间: |
|
查看次数: |
54 次 |
最近记录: |