reactjs - 为什么我收到“无法读取未定义的属性‘状态’”错误?
问题描述
这是代码:
class QuoteBox extends React.Component {
constructor(props){
super(props);
this.state = {
quotes: Data,
current: Data[0]
}
}
setRandomQuote(){
const index = Math.floor(Math.random() * this.state.quotes.length);
this.setState({
current: this.state.quotes[index]
})
}
render(){
return <div id="quote-box">
<p id="text">
{this.state.current.quote}
</p>
<h5 id="auther">
{this.state.current.author}
</h5>
<button onClick={this.setRandomQuote} id="new-quote">New Quote</button>
<a href="" id="tweet-quote">haha</a>
</div>
}
};
并收到此错误消息:
TypeError: Cannot read property 'state' of undefined
setRandomQuote
src/Components/QuoteBox/quoteBox.js:15
12 | }
13 |
14 | setRandomQuote(){
> 15 | const index = Math.floor(Math.random() * this.state.quotes.length);
| ^ 16 | this.setState({
17 | current: this.state.quotes[index]
18 | })
View compiled
▶ 19 stack frames were collapsed.
为什么在构造函数中初始化状态时未定义状态,我是新手,所以我想准确了解正在发生的事情和原因。谢谢。
解决方案
有几种方法可以解决这个问题,类组件最常见的两种方法是将函数绑定到组件或使用箭头函数。两者的例子如下。
构造函数中的函数绑定:
constructor(props){
super(props);
this.state = {
quotes: Data,
current: Data[0]
}
this.setRandomQuote = this.setRandomQuote.bind(this)
}
使用箭头函数:(感谢@Linda Paiste)
setRandomQuote = () => {
const index = Math.floor(Math.random() * this.state.quotes.length);
this.setState({
current: this.state.quotes[index]
})
}
但是,如果您刚刚开始,我强烈建议您使用函数式组件,并注意您阅读的任何使用基于类的组件的材料,因为它们可能已经过时了。
下面是您的类,重构为功能组件。确保从 react 中导入 {useState)。
const QuoteBox = () => {
const [state, setState] = useState({
quotes: Data,
current: Data[0]
})
const setRandomQuote = () => {
const index = Math.floor(Math.random() * state.quotes.length);
setState({
...state,
current: state.quotes[index]
})
}
return (<div id="quote-box">
<p id="text">
{state.current.quote}
</p>
<h5 id="auther">
{state.current.author}
</h5>
<button onClick={setRandomQuote} id="new-quote">New Quote</button>
<a href="" id="tweet-quote">haha</a>
</div>
)
};
推荐阅读
- xamarin.forms - Xamarin.Forms.Picker 内容在 UWP 中重复
- bitcoin - 需要帮助了解比特币原始交易
- google-cloud-platform - 您可以将 Google Cloud Web 控制台登录限制在 IP 地址范围内吗?
- python - 引用忽略反斜杠的文本正则表达式
- java - 打印列表的内容以及子列表
- reactjs - 如何计算复杂的 SQL 查询以响应后端并获取结果
- javascript - (React fetch data)这两者有什么区别
- java - 如何使用脚本化管道在詹金斯构建描述中添加超链接
- r - Tidy Eval:不可能在嵌套函数中使用 {{var}}?
- java - 高负载下的 Netty WorkerPool