[英]The button is supposed to bring a new random quote every time it’s clicked but nothing happens when I click it
我想在我的反應組件中包含一個按鈕元素,每次單擊它都會帶來一個新的隨機引用,但我被卡住了,因為當我單擊時按鈕沒有做任何事情。 這是針對免費代碼營隨機報價生成器挑戰的。 我想在我做任何樣式和其他任何事情之前確保按鈕工作。 我是新手,這是我的第一個挑戰
class App extends React.Component {
constructor(props) {
super(props);
this.state = { qoute: "", randomQoute: "" };
this.newQoute = this.newQoute.bind(this);
}
async componentDidMount() {
let response = await fetch("https://type.fit/api/quotes");
let data = await response.json();
this.setState({ qoute: data });
let randomIndex = Math.floor(Math.random() * data.length);
this.setState({ randomQoute: data[randomIndex] });
}
//this is the function that is called every time the button is clicked
newQoute() {
let randomIndex = Math.floor(Math.random() * qoute.length);
this.setState((state) => ({ randomQoute: state.qoute[randomIndex] }));
}
render() {
return (
<div>
<h1>Quotes</h1>
<h2>{this.state.randomQoute.text}</h2>
//this is the button element
<button onClick={this.newQoute}>New Qoute</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
在您提供您正在使用的完整文件后,我可以對其進行編輯。 截至目前,我看到了很多錯誤。 您有一個構造函數,但我沒有看到正在定義的類對象。 在您提供完整的類定義之前,我認為沒有人能夠提供幫助。
以及您收到的任何錯誤日志?
您沒有在以下函數中正確訪問 qoute 變量:
newQoute() {
let randomIndex = Math.floor(Math.random() * qoute.length);
this.setState((state) => ({ randomQoute: state.qoute[randomIndex] }));
}
在計算 randomIndex 時,您需要從狀態訪問 qoute 變量,如下所示: this.state.quote
確保使用this.state.[variableName]
訪問state
變量
所以你的功能將變成:
newQoute() {
let randomIndex = Math.floor(Math.random() * this.state.qoute.length);
this.setState((state) => ({ randomQoute: state.qoute[randomIndex] }));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.