【发布时间】:2020-01-16 08:05:12
【问题描述】:
在下面的代码中,我试图通过使用setstate() 来更改变量 i、x、y 和 z,但我不断收到错误消息,指出变量 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)); }
【问题讨论】:
-
你需要使用
this.setState({x : Math.floor(Math.Random() * 10)}) -
您在
this.setState中有错误。应该像@Code Maniac 所说的那样。有关更多用法,请参阅docs。 -
它是
Math.random()而不是Math.Random()
标签: javascript reactjs state