reactjs - React 无法将状态值传递给状态数组
问题描述
在 React 中,我有一个名为 random 的状态属性,带有一个随机值。我正在尝试选择具有随机状态的 myArray2 值并将其传递到 myArray 状态中。
当我单击按钮时,警报方法应该显示其中一个随机数,但它似乎不起作用。
import React, { Component } from 'react';
import './App.css';
class App extends Component {
//random = Math.floor(Math.random() * 3)
constructor(props){
super(props);
this.state = {
random: Math.floor(Math.random() * 3),
myArray2:['one','two','three'],
myArray:this.state.myArray2[this.state.random]
};
}
change = () => {
alert(this.state.myArray);
}
render() {
return (
<div className="App">
<button onClick={this.change}>ok</button>
</div>
);
}
}
export default App;
这就是我得到的——
TypeError:无法读取未定义的属性“myArray2”
这就是我要的-
显示随机数的警报方法
解决方案
这是目前基于类的组件无法做到的。但是,您可以让您的change()
函数自己执行随机逻辑并有效地更新 random 和 myArray 状态。
this.setState()
有第二个回调参数,它使我们能够访问更新的状态。使用它来触发警报。
this.state = {
random: Math.floor(Math.random() * 3),
myArray2:['one','two','three'],
myArray: null
};
change = () => {
const random = Math.floor(Math.random() * 3);
this.setState(
{
random: random,
myArray: this.state.myArray2[random]
},
() => alert(this.state.myArray) //now refers to the new state value
);
};
推荐阅读
- r - 按日期分组和计数 (R)
- python - 使用可变路径读取项目文件夹中的所有文件 - Python
- php - 标点符号以某种方式破坏 preg_match_all 组捕获
- php - 在 file_put_contents 之后取消链接
- printing - 信号打印 - 需要非常基本的帮助
- vue.js - 为什么Vue会更新父级中的变量-未使用事件
- javascript - 无法从 docker 运行 javascript 文件以使用 WSL shell (windows 10) 填充 mongo db
- node.js - 无法连接到在 Kubernetes 上运行的 Docker 容器中的套接字
- html - HTML 自定义组件 - 样式表问题
- mysql - laravel eloquent join where 子句与子查询以使用列名比较不起作用