我已经设法构建了一个react应用程序,该应用程序返回新报价而无需重复重复,但是现在,UI随着足够的单击事件而消失。为什么我的代码这样做?在控制台中,我会在发生这种情况时出现对象错误。
class QuoteMachine extends React.Component{
constructor(props){
super(props);
this.state = {
quote: fullQuote,
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
let copy = this.props.quotes.slice();
let index = Math.floor(Math.random() * copy.length);
this.setState(function(prevState,props){
if(prevState.quote != copy[index]){
return {quote: copy[index]}
}return {
quote: copy[index+1]}
})
}
render(){
const quote = this.state.quote[0];
const author = this.state.quote[1];
return (
<div id='quote-box'>
<div id='text'><h1> <div>{quote}</div> </h1></div>
<div id='author'><h3> <div>{author}</div> </h3></div>
<button onClick={this.handleClick} id='new-quote'>New Quote</button>
<a id='tweet-quote' href="https://twitter.com/intent/tweet">Tweet Me</a>
</div>
)
}
}
const QUOTES = [
["Stay Hungry. Stay Foolish.", "Steve Jobs"],
["Good Artists Copy, Great Artists Steal.", "Pablo Picasso"],
["Argue with idiots, and you become an idiot.", "Paul Graham"],
["Be yourself; everyone else is already taken.", "Oscar Wilde"],
["Simplicity is the ultimate sophistication.", "Leonardo Da Vinci"]
];
const fullQuote = QUOTES[Math.floor(Math.random() * QUOTES.length)]
ReactDOM.render(<QuoteMachine quotes={QUOTES} />,
document.getElementById('node'))
是因为您的索引从copy
的数组中?