【发布时间】:2019-07-13 09:08:17
【问题描述】:
在 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”
这就是我想要的-
显示随机数的警报方法
【问题讨论】:
-
对于每个请求,您应该传递新的随机整数,在本例中,随机填充一次随机整数,并且不会因每个请求而更改
-
@Pleinair,集成解决方案运气好吗?
标签: reactjs