const questions = [
"오늘 먹은 음식은?",
"오늘 기록하고 싶은 일은?",
"오늘을 한 단어로 정리하자면?",
"오늘 만난 사람은?",
"오늘 나에게 하고 싶은 말이 있다면?",
];
const getRandomIndex = (length: number): number => {
return Math.floor(Math.random() * length);
};
const TodayPost = {
postQuestions: [
{
question: "hi",
content: content1,
imgCount: imgFile.length,
videoCount: videoFile.length,
},
{
question: "hello",
content: content2,
imgCount: imgFile.length,
videoCount: videoFile.length,
},
],
todayFeeling: todayFeeling,
};
const TodayPost = {
postQuestions: [
{
question: "hi",
content: content1,
imgCount: imgFile.length,
videoCount: videoFile.length,
},
{
question: "hello",
content: content2,
imgCount: imgFile.length,
videoCount: videoFile.length,
},
],
todayFeeling: todayFeeling,
};
이렇게 작성했는데 value 를 작성할 때 마다 react가 새로고침 되어 랜덤 질문이 계속 변경되는 문제 발생
Solution
역시 stackoverflow에는 모든 답이 있다..
const questions = [
"오늘 먹은 음식은?",
"오늘 기록하고 싶은 일은?",
"오늘을 한 단어로 정리하자면?",
"오늘 만난 사람은?",
"오늘 나에게 하고 싶은 말이 있다면?",
];
const getRandomQuestion = (): string => {
return questions[Math.floor(Math.random() * questions.length)];
};
const [question1, setQuestion1] = useState<string>(getRandomQuestion());
const [question2, setQuestion2] = useState<string>(getRandomQuestion());
이렇게 아예 state 초기값을 설정해주고
랜덤 질문을 보여주고
<p>{question1}</p>
<input
type="text"
placeholder="내용 입력하기"
value={content1}
onChange={(e) => setContent1(e.target.value)}
/>
<input type={"file"} onChange={handleImgFile} multiple />
<input type={"file"} onChange={handleVideoFile} multiple />
onClick 했을 때 함수에 아래 코드를 넣어주어 setQuestion으로 저장!
const randomQuestion = getRandomQuestion();
setQuestion1(randomQuestion);
setQuestion2(randomQuestion);
위에서 setQuestion에 직접적으로 넣으려고 한것도 함수 스코프를 잘 생각해주어 넣었더라면 되었을 것 같다.
역시 스코프 중요성을 이번에 또 배우고 간다…
'Problem&Solution' 카테고리의 다른 글
객체 비교에서 한 실수 (1) | 2024.05.02 |
---|---|
uuid를 map의 key값으로 사용하고 생긴 문제점 (0) | 2024.05.02 |
회원가입에서 생기는 고민 (0) | 2023.01.09 |
axios get해올 때 data를 담는 법 (0) | 2022.12.23 |
API get 해오면서 발생한 협업 문제와 해결 과정 (0) | 2022.11.24 |