简体   繁体   English

从State React.JS渲染随机项

[英]Render Random Item from State React.JS

Given some items stored in state, I want to be able to click a button and display a random item from that array. 给定一些状态存储的项目,我希望能够单击一个按钮并显示该数组中的随机项目。 So far it only works on the first click and then it displays the same one letter after the first click. 到目前为止,它仅在第一次单击时有效,然后在第一次单击后显示相同的字母。

What exactly is going on? 到底是怎么回事?

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>
    )
  }
}

You're overwriting the notes array in state in your handleClick method. 您将在handleClick方法中覆盖处于状态的notes数组。 Try using a different key (something like activeNote ) in handleClick , then use that in your render method rather than this.state.notes . 尝试在handleClick使用其他键(例如activeNote类的activeNote ),然后在渲染方法中使用此键,而不要在this.state.notes

Add selected note handling 添加选定的笔记处理

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>
    )
  }
}

So I think I solved it. 所以我想我解决了。

I ended up adding another state key randomWord and setting it equal to '' . 我最终加入另一个国家重点randomWord并设置它等于''

I then set the state of randomWord to that of this.state.notes when randomized. 然后我设置的状态randomWord到的this.state.notes随机时。

Finally, I rendered this.state.randomWord 最后,我渲染了this.state.randomWord

No clue if that's the correct approach but it's a working solution, lol. 不知道这是否是正确的方法,但这是一个可行的解决方案,大声笑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM