繁体   English   中英

当将 array.length 传递给 reactjs 中的 function 时,它给出了 undefined

[英]when passing array.length to a function in reactjs it gives undefined

 const GetRandomInt = ({max}) => { console.log(max) return Math.floor(Math.random() * (max)) } const Button = (props) => { return ( <button onClick={props.handleClick}> {props.text} </button> ) } const Display = (props) => { return ( <div> {props.text} </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 10 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,'. 'Programming without an extremely heavy use of console,log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients' ] const [selected. setSelected] = useState(0) const len = anecdotes.length console.log(len) const handleClick = () => { console.log(Math.floor(Math.random() * (anecdotes.length))) const index = GetRandomInt(len) // Math.floor(Math.random() * (anecdotes.length)) while (index === selected) { index = GetRandomInt(len) // Math.floor(Math.random() * (anecdotes.length)) } setSelected(index) } return ( <div> <h1>Anecdote of the day</h1> <Display text={anecdotes[selected]} /> <Button handleClick={handleClick} text={'Next anecdote'} /> {/* {anecdotes[selected]} */} </div> ) }

上面的代码将三个值打印到控制台

  1. 包含数组长度的赋值变量
  2. 直接使用数组长度创建随机 integer
  3. 将值传递给 function 以在步骤 2 中使用 function 实现相同的效果

有人能告诉我为什么会这样吗? 我是否错误地传递了数据类型不匹配或其他的值? 我是 reactjs 的新手并通过课程学习,这是我遇到的练习之一。

该缺陷存在于您的GetRandomInt function 中。 它目前需要一个具有max属性的 object,并且您正在向它传递一个数字。

重写为

const GetRandomInt = (max) => {
  console.log(max)
  return Math.floor(Math.random() * (max))
}

参数名称周围的花括号本质上是告诉 function “获取给定的第一个参数的属性max ”,而在您的情况下,您需要参数本身,而不是其max属性。

您可以在此处阅读有关 object 解构的更多信息

暂无
暂无

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

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