【发布时间】:2021-02-01 12:47:57
【问题描述】:
我有一个名为 Calendar 的功能组件,其中每个月都是一个按钮。我设计的 API 以以下格式发送数据:
[
{
"month": 1,
"count": 5
},
{
"month": 3,
"count": 2
},
{
"month": 10,
"count": 4
},
{
"month": 11,
"count": 3
}
]
现在我有以下状态:
const [jan, setJan] = useState(0);
const [feb, setFeb] = useState(0);
const [mar, setMar] = useState(0);
const [apr, setApr] = useState(0);
const [may, setMay] = useState(0);
const [june, setJune] = useState(0);
const [july, setJuly] = useState(0);
const [aug, setAug] = useState(0);
const [sept, setSept] = useState(0);
const [oct, setOct] = useState(0);
const [nov, setNov] = useState(0);
const [dec, setDec] = useState(0);
const [month, setMonth] = useState([]);
使用useEffect,我已经设置了月份并将数据存储在月份状态,但是当我使用console.log(month)时它显示一个空数组,
useEffect(() => {
axios.get("http://localhost:8081/api/CalendarNotification/1234")
.then(res => {
setMonth(res.data)
})
.catch(err => { console.log(err) })
}, []);
现在我已经使用下面的代码,根据从 api 接收到的数据中的“月份”来设置每个月的状态。
{
(month.map(mon => {
if (mon["month"] === 1)
setJan(mon["count"]);
else if (mon["month"] === 2)
setFeb(mon["count"]);
else if (mon["month"] === 3)
setMar(mon["count"]);
else if (mon["month"] === 4)
setApr(mon["count"]);
else if (mon["month"] === 5)
setMay(mon["count"]);
else if (mon["month"] === 6)
setJune(mon["count"]);
else if (mon["month"] === 7)
setJuly(mon["count"]);
else if (mon["month"] === 8)
setAug(mon["count"]);
else if (mon["month"] === 9)
setSept(mon["count"]);
else if (mon["month"] === 10)
setOct(mon["count"]);
else if (mon["month"] === 11)
setNov(mon["count"]);
else if (mon["month"] === 12)
setDec(mon["count"]);
}
))}
还有,我在哪里写代码,在useEffect还是return方法,请告诉我!
但是没有任何效果,有人可以帮忙吗? 提前致谢! :)
【问题讨论】:
-
“当我使用 console.log(month) 时,它显示一个空数组” - 这个 console.log 语句在哪里?请记住,状态是异步更新的,因此如果您在调用
setMonth后立即尝试记录month,它将记录month的旧值
标签: reactjs api react-hooks api-design use-effect