在下面的代码中,我试图通过使用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)); }
答案 0 :(得分:0)
对于您的状态,您需要传递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()
-我在这里为您更正了它:)