javascript - 尝试在 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)); }
解决方案
对于您的状态,您需要传递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()
- 我已经在这里为你更正了:)
推荐阅读
- pagespeed - LCP评分需要改进
- java - Spring Boot 中的嵌入式 tomcat 突然进入 100% CPU 利用率
- javascript - 如何使用 firebase reactjs 更新行属性
- python - 如何连接到WiFi?
- python - 仅使用 generics.RetrieveUpdateDestroyAPIView 的一个字段的补丁
- ios - Apple 文档中的“场景支持”到底是什么意思?
- python - 从列表中删除括号和引号
- mongodb - 使用 Meteor 方法从 MongoDB 下载大量文档
- python - 给多个字典我可以得到每个键的最低(或最高)值吗?
- r - 如何添加具有两个不同轴变量的变量