Javascript 从State React.JS呈现随机项
给定一些存储在状态中的项目,我希望能够单击按钮并显示该数组中的随机项目。到目前为止,它只在第一次单击时起作用,然后在第一次单击后显示相同的一个字母 到底发生了什么Javascript 从State React.JS呈现随机项,javascript,reactjs,Javascript,Reactjs,给定一些存储在状态中的项目,我希望能够单击按钮并显示该数组中的随机项目。到目前为止,它只在第一次单击时起作用,然后在第一次单击后显示相同的一个字母 到底发生了什么 import React, { Component } from 'react' export default class App extends Component { constructor(props) { super(props) this.state = { notes: ['hey',
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>
)
}
}
import React,{Component}来自“React”
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具)
此.state={
注意:['hey','yo','sup'],
单击:false
}
}
handleClick=()=>{
这是我的国家({
对,,
注释:this.state.notes[Math.floor(Math.random()*
this.state.notes.length)]
})
}
render(){
返回(
随机音符
{this.state.clicked?this.state.notes:'}
)
}
}
您正在覆盖handleClick
方法中处于状态的notes
数组。尝试在handleClick
中使用不同的键(比如activeNote
),然后在渲染方法中使用它,而不是this.state.notes
,所以我想我解决了它
我最后添加了另一个状态键randomWord
,并将其设置为'
然后我将randomWord
的状态设置为随机化时的this.state.notes
最后,我呈现了this.state.randomWord
不知道这是不是正确的方法,但这是一个有效的解决方案,哈哈。添加选定的注释处理
import React, { Component } from 'react'
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
notes: ['hey', 'yo', 'sup'],
selectedNote: null,
clicked: false
}
}
handleClick = () => {
this.setState({
clicked: true,
selectedNote: 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.selectedNote}</h1>
</div>
)
}
}
import React,{Component}来自“React”
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具)
此.state={
注意:['hey','yo','sup'],
selectedNote:null,
单击:false
}
}
handleClick=()=>{
这是我的国家({
对,,
selectedNote:this.state.notes[Math.floor(Math.random()*
this.state.notes.length)]
})
}
render(){
返回(
随机音符
{this.state.clicked&&this.state.selectedNote}
)
}
}
您预期会发生什么?this.state.notes是一个数组,但在handleClick函数中,您正在将注释设置为字符串,因为“h”[0]
是“h”
?您可以通过一个随机注释重写注释。再添加一个字段f e randomNode:null并在其中写入随机注释并在render()中显示。感谢您的回复。我不知道你的确切意思。你能给我一点代码片段吗?