React随机名言生成器按钮点击无响应问题求助(Free Code Camp挑战)
解决React随机名言按钮无响应问题
你的按钮点击无响应的核心问题是**newQoute函数中引用了未定义的变量**,直接修改函数即可修复:
错误点分析
在newQoute方法里,你写了Math.random() * qoute.length,但这里的qoute并没有在当前作用域定义——所有名言数据都存在组件的state.qoute里,必须通过this.state来访问。
另外还有两个小细节需要修正:
- JSX中的单行注释不能用
//,要写成{/* 注释内容 */},否则会被当作文本渲染到页面上 - 变量名拼写:
qoute是拼写错误,正确的是quote(这个不影响功能,但建议修正以保持代码规范)
修正后的完整代码
class App extends React.Component { constructor(props) { super(props); // 修正变量名拼写:qoute → quote this.state = { quote: "", randomQuote: "" }; this.newQuote = this.newQuote.bind(this); } async componentDidMount() { let response = await fetch("https://type.fit/api/quotes"); let data = await response.json(); // 对应修改state的属性名 this.setState({ quote: data }); let randomIndex = Math.floor(Math.random() * data.length); this.setState({ randomQuote: data[randomIndex] }); } // 修正函数名拼写,同时修改引用state的方式 newQuote() { // 从this.state中获取名言数组长度 let randomIndex = Math.floor(Math.random() * this.state.quote.length); this.setState((state) => ({ randomQuote: state.quote[randomIndex] })); } render() { return ( <div> <h1>Quotes</h1> <h2>{this.state.randomQuote.text}</h2> {/* JSX中正确的单行注释写法 */} <button onClick={this.newQuote}>New Quote</button> </div> ); } } ReactDOM.render(<App />, document.getElementById("root"));
关键修改说明
- 所有
qoute拼写统一修正为quote,避免混淆 newQuote函数中,将qoute.length改为this.state.quote.length,确保能正确获取名言数组的长度来生成随机索引- 修正JSX中的注释格式,避免页面出现多余文本
现在点击按钮就能正常加载新的随机名言了。
内容的提问来源于stack exchange,提问作者Musinga
相关产品推荐
相关产品推荐

