首页 > 解决方案 > 尝试在 React 中更改状态时出现未定义的错误

问题描述

在下面的代码中,我试图通过使用来更改变量 i、x、y 和 z setstate(),但我不断收到错误消息,指出变量 i、x、y 和 z 是“未定义的”。有没有人对为什么会发生这种情况有任何建议?

state = {
albumArt: [
  {title: "Supermodel", image: "AlbumImages/1.jpg"},
  {title: "A Moment Apart", image: 'AlbumImages/2.jpg'},
  {title: "Beerbongs and Bentleys", image: 'AlbumImages/3.jpg'},
  {title: "Another Eternity", image: 'AlbumImages/4.jpg'},
  {title: "Astroworld", image: 'AlbumImages/5.jpg'},
  {title: "The Story of Us", image: 'AlbumImages/6.jpg'},
  {title: "Slow Motion", image: 'AlbumImages/7.jpg'},
  {title: "Free Spirit", image: 'AlbumImages/8.jpg'},
  {title: "Birds in the Traps Sing McKnight", image: 'AlbumImages/9.jpg'},
  {title: "At. Long. Last. A$ap", image: 'AlbumImages/10.jpg'}
],

  otherStateI: 0,
  x: 0,
  y: 0,
  z: 0 }

randomAlbum = () => {
this.setState(i = Math.floor(Math.Random() * 10));
this.setState(x = Math.floor(Math.Random() * 10));
this.setState(y = Math.floor(Math.Random() * 10));
this.setState(z = Math.floor(Math.Random() * 10)); }

标签: javascriptreactjsstate

解决方案


对于您的状态,您需要传递setState一个带有要更改的道具/值的对象(或返回该对象的函数)

this.setState({ i: Math.floor(Math.random() * 10) });
// ...etc

在您的特定代码中,一次传递它们也更有意义:

this.setState({ 
    i: Math.floor(Math.random() * 10),
    x: Math.floor(Math.random() * 10),
    y: Math.floor(Math.random() * 10),
    z: Math.floor(Math.random() * 10),
});

哦,PS -Math.random()不是Math.Random()- 我已经在这里为你更正了:)


推荐阅读