I am learning React and Javascript, I am writing a small app that have 40 squares with different colors and every second 2 colors will randomly change, everything works fine but I have one minor problem. How can I change my code so that if two numbers are the same one of them will be regenerated? I tried to use if like this
import React from 'react';
import ReactDom from 'react-dom';
const totalColor=40;
const Box=(props)=>{...}
class RandomColorApp extends React.Component{
constructor(props){
super(props);
const boxes = new Array(totalColor).fill().map(this.randomColor,this);
this.state={boxes}
setInterval(()=>{
const randomIndex1=Math.floor(Math.random()*3)
const randomIndex2=Math.floor(Math.random()*3)
if(randomIndex1!==randomIndex2){
console.log(randomIndex1,randomIndex2)
}
},1000);
}
randomColor(){...}
render(){...}
}
RandomColorApp.defaultProps={colors:[...]}
ReactDom.render(<RandomColorApp/>,document.getElementById('app'));
the whole process will be delayed by 1 second before it regenerates new numbers, and also is there a way I can refactor the code so I do not have to repeat Math.floor(Math.random()*3) too much in case I need more than 2 random numbers, thank you verymuch
Aucun commentaire:
Enregistrer un commentaire