Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React setState in render()

Tags:

reactjs

I want to let the user enter game mode and pass that data as props to the Board but when I do like below, React just enters the infinite loops. How should I re-organize my code to use setState() for humanFirst and pvp? Any idea is appreciated.

export default class Game extends Component {
    constructor(props) {
        super(props);
        this.state = {
            humanFirst: true,
            pvp: true,
            xIsNext: true,
            stepNumber: 0,
            history: [
                { squares: Array(9).fill(null) }
            ]
        }
    }
render() {
return (
<div>
<Board/>
<div className="game-info">                  
                    <label>Choose game mode</label>
                    <br/>
                    <select >
                        <option  onSelect={this.setState({
                            humanFirst: true,
                            pvp: true
                        })}>Human vs Human</option>
                        <option>Human first</option>
                        <option>AI first</option>
                    </select>
                    <br/>
                    <button type="submit">Start Game</button>
 </div>
</div>

)


}
like image 257
BestYasuo Avatar asked Dec 06 '25 07:12

BestYasuo


1 Answers

You set the state at the moment the component is rendered, which cause an infinite loop, because changing state causes another render.

<option  onSelect={this.setState({
                            humanFirst: true,
                            pvp: true
                        })}>Human vs Human</option>

Instead, you probably want the state to be changed when the event is fired:

<option  onSelect={() => this.setState({
                            humanFirst: true,
                            pvp: true
                        })}>Human vs Human</option>
like image 195
Pandaiolo Avatar answered Dec 08 '25 20:12

Pandaiolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!