質問編集履歴
1
具体例を追加した
title
CHANGED
@@ -1,1 +1,1 @@
|
|
1
|
-
next jsで
|
1
|
+
next jsでuseStateを使うと無限ループになってしまいます
|
body
CHANGED
@@ -4,44 +4,28 @@
|
|
4
4
|
現在が1~7月の場合 -> starAtを前年8月、endAtを今年の7月
|
5
5
|
現在が8~12月の場合 ->starAtを今年の8月、endAtを来年の7月
|
6
6
|
にしたいです。
|
7
|
+
### エラーメッセージ
|
8
|
+
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
|
9
|
+
と無限ループになりエラーになっています。
|
7
10
|
### 試したこと
|
8
|
-
|
11
|
+
ネットで調べたら関数にしたらいいと書いてあってやってみたのですが、ダメでした
|
9
|
-
となり、使うことができませんでした
|
10
12
|
```typescript
|
11
|
-
if (1<=DateTime.local().month&&DateTime.local().month <= 7) {
|
12
|
-
|
13
|
+
function axx() {
|
13
|
-
|
14
|
+
setStartAt(
|
14
|
-
|
15
|
+
DateTime.local()
|
15
|
-
|
16
|
+
.set({ month: 8 })
|
16
|
-
|
17
|
+
.minus({ year: 1 })
|
17
|
-
|
18
|
+
.toJSDate(),
|
18
|
-
),
|
19
19
|
);
|
20
|
-
const [endAt, setEndAt] = useState(
|
21
|
-
|
20
|
+
setEndAt(
|
22
|
-
|
21
|
+
DateTime.local()
|
23
|
-
|
22
|
+
.set({ month: 7 })
|
24
|
-
.plus({ year: 1 })
|
25
|
-
|
23
|
+
.toJSDate(),
|
26
|
-
),
|
27
24
|
);
|
28
|
-
} else {
|
29
|
-
const [startAt, setStartAt] = useState(
|
30
|
-
startOfMonth(
|
31
|
-
DateTime.local()
|
32
|
-
.set({ month: 8 })
|
33
|
-
.toJSDate(),
|
34
|
-
),
|
35
|
-
);
|
36
|
-
const [endAt, setEndAt] = useState(
|
37
|
-
endOfMonth(
|
38
|
-
DateTime.local()
|
39
|
-
.set({ month: 7 })
|
40
|
-
.plus({ year: 1 })
|
41
|
-
.toJSDate(),
|
42
|
-
),
|
43
|
-
);
|
44
25
|
}
|
26
|
+
if (1 <= nowMonth && nowMonth <= 7) {
|
27
|
+
axx();
|
28
|
+
}
|
45
29
|
```
|
46
30
|
|
47
31
|
### 該当のソースコード
|
@@ -52,19 +36,41 @@
|
|
52
36
|
|
53
37
|
export default function Index() {
|
54
38
|
const [startAt, setStartAt] = useState(
|
55
|
-
|
39
|
+
startOfMonth(
|
56
|
-
|
40
|
+
DateTime.local()
|
57
|
-
|
41
|
+
.set({ month: 8 })
|
58
|
-
|
42
|
+
.toJSDate(),
|
59
|
-
|
43
|
+
),
|
44
|
+
);
|
45
|
+
const [endAt, setEndAt] = useState(
|
46
|
+
endOfMonth(
|
47
|
+
DateTime.local()
|
48
|
+
.set({ month: 7 })
|
49
|
+
.plus({ year: 1 })
|
50
|
+
.toJSDate(),
|
51
|
+
),
|
52
|
+
);
|
53
|
+
const nowMonth =
|
54
|
+
DateTime.local()
|
55
|
+
.toJSDate()
|
56
|
+
.getMonth() + 1;
|
57
|
+
|
58
|
+
if (1 <= nowMonth && nowMonth <= 7) {
|
59
|
+
setStartAt(
|
60
|
+
DateTime.local()
|
61
|
+
.set({ month: 8 })
|
62
|
+
.minus({ year: 1 })
|
63
|
+
.toJSDate(),
|
60
64
|
);
|
61
|
-
const [endAt, setEndAt] = useState(
|
62
|
-
|
65
|
+
setEndAt(
|
63
|
-
|
66
|
+
DateTime.local()
|
64
|
-
|
67
|
+
.set({ month: 7 })
|
65
|
-
.plus({ year: 1 })
|
66
|
-
|
68
|
+
.toJSDate(),
|
67
|
-
),
|
68
69
|
);
|
70
|
+
}
|
71
|
+
return(
|
72
|
+
<input type='month value={strtAt}/>
|
73
|
+
<input type='month value={endAt}/>
|
74
|
+
)
|
69
75
|
}
|
70
76
|
```
|