类型错误:无法读取 react 中未定义数组洗牌的属性'length'



我是 React 的新手,我正在尝试弄清楚如何洗牌数组。我已经尝试了不同的方法来洗牌数组,但问题始终在于长度。 TypeError: Cannot read property 'length' of undefined .我不确定为什么会发生这种情况,或者我应该如何在 React 中处理它。对我来说,这不应该是 React 的问题,但我也不知道。当一切正常时会发生什么:

你点击"hard"按钮,它应该渲染数组挑战中的前两个元素,每次你点击这个按钮时,数组都应该被洗牌。

你有什么想法可以帮助我吗?

这是代码:

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

最新更新