我想在每个onClick上返回新的报价,而不重复报价。
为此,我将跟踪quotes数组的状态,并在每次触发handleClick()时,将quotes拼接到quotes数组之外,然后将新数组作为状态返回。当quotes数组的长度小于1时,我将quotes数组的state属性重置为新的引号副本。
但是,这带来了另一个问题。如果引号是数组中的最后一个引号和新数组中的第一个引号,则可能会重复。
class QuoteMachine extends React.Component{
constructor(props){
super(props);
this.state = {
copy: props.quotes.slice(),
author: fullQuote[0],
quote: fullQuote[1],
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
const copy = this.props.quotes.slice();
const index = Math.floor(Math.random() * copy.length);
const newCopy = (this.state.copy.length > 1) ? copy.splice(index,1) :
copy;
const item = copy[index];
this.setState({
author: item[0],
quote: item[1],
copy: newCopy
})
}
render(){
return (
<div id='quote-box'>
<div id='text'><h1> {this.state.author} </h1></div>
<div id='author'><h3> {this.state.quote} </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'))
编辑:因此,我听取了您的建议,将两个引号进行比较,并将handleClick()方法更改为此:
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]}
})
}
这将在每个单击事件上返回新的引用,但是当我不断单击按钮时会弹出一个新问题:最终,当我单击足够的次数时,整个UI就会消失。我对为什么会这样感到非常困惑。