【发布时间】:2018-04-08 04:26:55
【问题描述】:
给定一些存储在状态中的项目,我希望能够单击一个按钮并显示该数组中的一个随机项目。到目前为止,它只适用于第一次点击,然后在第一次点击后显示相同的一个字母。
到底发生了什么?
import React, { Component } from 'react'
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
notes: ['hey', 'yo', 'sup'],
clicked: false
}
}
handleClick = () => {
this.setState({
clicked: true,
notes: this.state.notes[Math.floor(Math.random() *
this.state.notes.length)]
})
}
render() {
return (
<div className="App">
<button onClick={this.handleClick}>Random Note</button>
<h1>{this.state.clicked ? this.state.notes : ''}</h1>
</div>
)
}
}
【问题讨论】:
-
您预计会发生什么? this.state.notes 是一个数组,但是在您的 handleClick 函数中,您将注释记为一个字符串
-
因为
"h"[0]是"h"? -
你用一个随机笔记重写笔记。再添加一个字段 f e randomNode: null 并在其中写入随机注释并在render()中显示。
标签: javascript reactjs