Reputation: 449
In React i have state property called random with a random value. I'm trying to select myArray2 value with random state and pass it inside myArray state.
When i click button, alert method should show one of the random numbers but it doesn't seem to be working.
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;
THIS IS WHAT I GET-
TypeError: Cannot read property 'myArray2' of undefined
THIS IS WHAT I WANT-
alert method showing random number
Upvotes: 0
Views: 402
Reputation: 15688
This is something you currently cannot do with a class-based component. You can however just have your change()
function execute the random logic on its own and effectively update the random and myArray state.
this.setState()
has a 2nd argument for call-backs which gives us access to the updated state. Use it to trigger the alert.
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
);
};
See sandbox for reference: https://codesandbox.io/s/confident-meadow-jumty
Upvotes: 4
Reputation: 1674
Your mistake is calling state inside state and trying to change value of state property without setState. I think you should want this
import React, { Component } from "react";
import ReactDOM from "react-dom";
class App extends Component {
state = {
myArray2: ["one", "two", "three"],
myArray: []
};
change = () => {
let random = Math.floor(Math.random() * 3);
this.setState({ myArray: this.state.myArray2[random] });
alert(this.state.myArray);
};
render() {
return (
<div className="App">
<button onClick={this.change}>ok</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Upvotes: 0