【问题标题】:Function in React fires but it's not being calledReact 中的函数触发但没有被调用
【发布时间】:2021-08-05 14:36:37
【问题描述】:

我正在研究 Fullstack Open 的第 1 部分,即轶事练习,我无法弄清楚为什么当我按下的按钮不应该触发该功能时某个功能会触发。您将在下面看到,我创建了一个generateRand 函数,它生成一个不大于anecdotes 数组长度的随机数。 handleNext 函数调用generateRand 并将selected 的状态设置为generateRand 的值,以便从数组中挑选一个轶事。一个单独的函数handleVote 允许用户为当前轶事投票。我不确定为什么当我按下投票时,它会触发 generateRand,而 handleVote 是我按下投票按钮时调用的函数。

App.js

import React, { useState } from 'react'

const Button = ({ handleClick, text }) => {
    return (
        <button style={{ margin:'5px' }} onClick={handleClick}>
        {text}
        </button>
    )
}

const Anecdote = ({ anecdotes, selected }) => {
    return (
        <div>
            {anecdotes[selected]}
        </div>

    )
}

const App = () => {
    const anecdotes = [
        'If it hurts, do it more often',
        'Adding manpower to a late software project makes it later!',
        'The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
        'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
        'Premature optimization is the root of all evil.',
        'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.'
    ]
   

    const [selected, setSelected] = useState(0)
    // const [trackVotes, setVote] = useState([])
    const [points, setPoints] = useState({0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0})

    // Generate random number
    const generateRand = () => {
        const max = anecdotes.length
        const random = Math.floor(Math.random()* max)
        console.log('generateRand fired')
        return random
    }

    const handleNext = () => { 
        setSelected(generateRand()) 
        console.log('handleNext fired.')
  }

    const handleVote = () => {
        const copy = { ...points }
        copy[selected] += 1
        setPoints(copy)
        console.log('handleVote fired.')
    }
    

  return (
    <div>
      <Anecdote anecdotes={anecdotes} selected={generateRand()}/>
      <Button handleClick={handleVote} text="vote"/>
      <Button handleClick={handleNext} text="next anecdote"/>
    </div>
  )
}

export default App

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    generateRand() 在每次渲染时都会被调用,因为你已经像这样传递了它。

    <Anecdote anecdotes={anecdotes} selected={generateRand()}/>
    

    因此,每当您单击投票按钮时,它都会触发handleVote,您在其中setPoints,导致重新渲染并因此再次调用generateRand()

    你应该把它改成

    <Anecdote anecdotes={anecdotes} selected={selected}/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      • 2023-02-12
      • 1970-01-01
      相关资源
      最近更新 更多