【问题标题】:React Hook not notifying state change to components using the hookReact Hook 不使用钩子通知组件的状态更改
【发布时间】: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 时不会更新。

我还可以在控制台中看到来自 API 调用的承诺。

【问题讨论】:

  • 你想要一个共同的状态,它可以使用钩子更新所有组件中的数据

标签: reactjs react-hooks react-state-management


【解决方案1】:

要为 useState 更新对象,推荐的方法是使用回调和传播运算符。

updateDates((prevState) => {...prevState, to:e, from:s});

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多