【问题标题】:Render Random Item from State React.JS从状态 React.JS 渲染随机项目
【发布时间】: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


【解决方案1】:

添加选定的笔记处理

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

【讨论】:

    【解决方案2】:

    您在handleClick 方法中覆盖notes 数组。尝试在handleClick 中使用不同的键(例如activeNote),然后在您的渲染方法中使用它而不是this.state.notes

    【讨论】:

    • 感谢您的回复。我不确定你到底是什么意思。能给我一个小代码sn-p吗?
    【解决方案3】:

    所以我想我解决了。

    我最终添加了另一个状态键 randomWord 并将其设置为等于 ''

    然后我将randomWord 的状态设置为this.state.notes 随机时的状态。

    最后,我渲染了this.state.randomWord

    不知道这是否是正确的方法,但这是一个可行的解决方案,哈哈。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 2015-04-26
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多