[英]TypeError: Cannot read property 'length' of undefined array shuffle in react
我是React的新手,我想弄清楚如何对数组进行随机组合。 我尝试过不同的方法来洗牌数组,但问题总是与长度有关。 TypeError: Cannot read property 'length' of undefined
。 我不确定为什么会这样或我应该如何在React中处理它。 对我来说,这应该不是React的问题,但我也不知道。 当一切正常时会发生什么:
您单击“硬”按钮,它应呈现数组质询的前两个元素,并且每次单击该按钮时,都应对数组进行混洗。
您有什么想法可以帮助我吗?
这是代码:
import React from 'react';
import ReactDOM from 'react-dom';
let era = [
60, 70, 80, 90, 2000
]
let genre = [
'Rock', 'Pop', 'Jazz', 'Country'
]
let challenge = [
'LikeElvis', 'Parent\'s favourite songs', 'too high for me'
]
class Karaoke extends React.Component {
constructor(props){
super(props);
this.state = {
'easy': '',
'easyChallenge': '',
'hard': '',
'hardChallenge': '',
'hardEra': ''
}
};
selectEasy = () => {
let genreSelected = [];
let challengeSelected = [];
genreSelected.push(genre[Math.floor(Math.random() * genre.length)]);
this.setState({"easy": genreSelected})
challengeSelected.push(challenge[Math.floor(Math.random() * challenge.length)]);
this.setState({"easyChallenge": challengeSelected})
}
selectHard = () => {
let genreSelected = [];
let challengeSelected = [];
let eraSelected = [];
genreSelected.push(genre[Math.floor(Math.random() * genre.length)]);
eraSelected.push(era[Math.floor(Math.random() * era.length)]);
this.setState({ "hard": genreSelected} );
this.setState({ "hardEra": eraSelected} );
this.setState({ "hardChallenge": challengeSelected} );
challengeSelected.push(challenge.slice(0, 2))
console.log(challengeSelected);
}
shuffle = (challenge) => {
let i = challenge.length, temporaryValue, randomIndex;
while (0 !== i) {
randomIndex = Math.floor(Math.random() * i);
i -= 1;
temporaryValue = challenge[i];
challenge[i] = challenge[randomIndex];
challenge[randomIndex] = temporaryValue;
}
return challenge
}
click = () => {
this.selectHard();
this.shuffle();
}
render = () => {
return(
<div>
<button onClick={this.selectEasy}>Easy</button>
<button onClick={this.click}>Hard</button>
<h1>the genre is {this.state.easy} </h1>
<h1>the challenge is {this.state.easyChallenge} </h1>
<h1>Hard mode: {this.state.hard} + {this.state.hardEra + '\'s'}</h1>
<h1>Hard mode challenge: {this.state.hardChallenge} </h1>
</div>
)
}
}
ReactDOM.render(<Karaoke />, document.getElementById('root'));
您正在定义期望参数的suffle
方法。 但是,当您从click
方法调用它时,您没有提供上述参数:
shuffle(challenge) {
// ...
}
click = () => {
// ...
this.shuffle();
}
这将导致声明的参数undefined
,并且suffle
方法不会默认设置全局challenge
变量。
要解决此问题,您需要从方法定义中删除参数,或者将其传递给click
函数:
shuffle() {
// ...
}
click = () => {
// ...
this.shuffle();
}
/* OR */
shuffle(challenge) {
// ...
}
click = () => {
// ...
this.shuffle(challenge);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.