나는 React와 Javascript를 배우고 있으며, 다른 색상과 40 개의 사각형을 가진 작은 응용 프로그램을 작성하고 있으며 매 2 초마다 2 개의 색상이 무작위로 바뀔 것입니다. 사소한 문제가 하나 있습니다. 두 개의 숫자가 같으면 다시 생성 될 수 있도록 코드를 어떻게 바꿀 수 있습니까? 내가 사용하려고하는 경우 등이두 개의 난수가 자바 스크립트에서 동일하지 않다는 것을 확인하는 방법
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'));
그러나 또한 새 번호를 다시 생성하고 이전 문제는, 전체 과정은 1 초 지연 될 것입니다 나는 내가이없는 코드를 리팩토링 할 수있는 방법이 반복 Math.floor (인 Math.random() * 3) 나는, 2 개 이상의 임의의 숫자를 필요로 내 전체 코드는 단지의 경우는
import React from 'react';
import ReactDom from 'react-dom';
const totalColor=4;
const Box=(props)=>{
const style={
width: '180px',
height: '180px',
display: 'inline-block',
backgroundColor: props.color
}
return <div style={style}/>
}
class RandomColorApp extends React.Component{
constructor(props){
super(props);
const boxes = new Array(totalColor).fill().map(this.randomColor,this);
this.state={boxes}
setInterval(()=>{
const boxes=this.state.boxes.slice();
const randomIndex1= Math.floor(Math.random()*boxes.length);
const randomIndex2= Math.floor(Math.random()*boxes.length);
boxes[randomIndex1]=this.randomColor();
boxes[randomIndex2]=this.randomColor();
this.setState({boxes});
//const randomIndex1=Math.floor(Math.random()*3)
//const randomIndex2=Math.floor(Math.random()*3)
//if(randomIndex1!==randomIndex2){
// console.log(randomIndex1,randomIndex2)
//}
},1000);
}
randomColor(){
let colorIndex=Math.floor(Math.random()*this.props.colors.length)
return this.props.colors[colorIndex];
}
render(){
const boxes=this.state.boxes.map((color,index)=>(
<Box key={index} color={color}/>
))
return(
<div className='RandomColorApp'>
{boxes}
</div>
);
}
}
RandomColorApp.defaultProps={...}
ReactDom.render(<RandomColorApp/>,document.getElementById('app'));
왜 생성자에서 setInterval을()를 추가 하시겠습니까? –
내가 어디에 넣어 줄 것을 제안해야합니까? 답변을 얻은 후에 모든 것이 자동으로 실행되고 onSubmit 양식은 물론 onClick 함수도 제공됩니다. – Nhat
알립니다. 답변을 추가했습니다. 희망을 당신의 질문을 해결할 것입니다. –