[英]React js error in a simple function that takes an array and returns a random value
I am getting an error that I am not able to figure, its about a function that takes an array and returns a random value from it.我收到一个我无法弄清楚的错误,它是关于一个函数,它接受一个数组并从中返回一个随机值。 I used the same function last time and there was no such error
我上次使用了相同的功能,没有出现这样的错误
helpers.js helpers.js
function choice(arr) {
let randomIndex = Math.floor(Math.random() * 3);
return arr[randomIndex];
}
export { choice };
box.js盒子.js
import React, { Component } from 'react';
import {choice} from './helpers';
import './Box.css'
class Box extends Component {
static defaultProps = {
allColors: ["purple", "magenta", "violet", "pink"]
};
constructor(props){
super(props);
this.state = {color: choice(this.props.allcolors)};
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
}
render(){
return(
<div className="Box" style={{backgroundColor: this.state.color}
} onClick={this.handleClick}>
</div>
);
}
}
export default Box;
There are two mistakes in your code:您的代码中有两个错误:
this.props.allcolors
is undefined
, because you have set the prop allColors
with uppercase "C" this.props.allcolors
是undefined
,因为你已经用大写的“C”设置了道具allColors
choice
, won't give you your desired result.choice
不会给您想要的结果。 It now only works correctly for arrays of length 3. To fix this, you could change 3
into arr.length
like so:3
更改为arr.length
如下所示:function choice(arr) {
let randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.