【发布时间】:2022-12-05 23:04:21
【问题描述】:
所以我有一个钩子
export default function useCustomHook() {
const initFrom = localStorage.getItem("startDate") === null? moment().subtract(14, "d"): moment(localStorage.getItem("startDate"));
const initTo = localStorage.getItem("endDate") === null? moment().subtract(1, "d"): moment(localStorage.getItem("endDate"));
const [dates, updateDates] = React.useState({
from: initFrom,
to: initTo
});
const [sessionBreakdown, updateSessionBreakdown] = React.useState(null);
React.useEffect(() => {
api.GET(`/analytics/session-breakdown/${api.getWebsiteGUID()}/${dates.from.format("YYYY-MM-DD")}:${dates.to.format("YYYY-MM-DD")}/0/all/1`).then(res => {
updateSessionBreakdown(res.item);
console.log("Updated session breakdown", res);
})
},[dates])
const setDateRange = (startDate, endDate) => {
const e = moment(endDate);
const s = moment(startDate);
localStorage.setItem("endDate", e._d);
localStorage.setItem("startDate", s._d);
updateDates({to:e, from:s});
}
const getDateRange = () => {
return [dates.from, dates.to];
}
return [sessionBreakdown, getDateRange, setDateRange]
}
现在,这个挂钩似乎在网络检查器中工作,如果我调用 setDateRanger 函数,我可以看到它调用了我们的 API 服务,并取回了结果。
但是,我们有几个组件正在使用 sessionBreakdown 返回结果,并且在使用 updateSessionBreakdown 时不会更新。
【问题讨论】:
-
你想要一个共同的状态,它可以使用钩子更新所有组件中的数据
标签: reactjs react-hooks react-state-management