localstorage item not cleared upon React component unmount

huangapple go评论69阅读模式
英文:

localstorage item not cleared upon React component unmount

问题

以下是您提供的代码的翻译部分:

我有一些React组件它们使用localstorage存储一些信息
这些与自定义钩子绑定到状态变量

export const useLocalStorage = (key, defaultValue) => {
    const [value, setValue] = useState(() => {
        return getStorageValue(key, defaultValue);
    });

    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);

    return [value, setValue];
}

组件使用它如下:

const [thing, setThing] = useLocalStorage('thing', '');

现在,我想要的是在组件卸载时清除它。

我尝试使用useEffect清除它:

useEffect(() => {
    return () => {
        setThing(prevThing => '');
    }
},[]);

然而,这似乎不起作用。我甚至可以在清除函数中记录控制台日志,但状态更改和随后的本地存储清除没有发生。我不确定如何正确清除它。

编辑(添加getStorageValue):

const getStorageValue = (key, defaultValue) => {
    let value;
    try {
        const saved = localStorage.getItem(key);
        value = JSON.parse(saved);

    } catch(err) {
        value = false;
    }

    return value || defaultValue;
}
英文:

I have some React components and they use localstorage to store some information.
These are tied to state variables with a custom hook:

export const useLocalStorage = (key, defaultValue) => {
    const [value, setValue] = useState(() => {
        return getStorageValue(key, defaultValue);
    });

    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);

    return [value, setValue];
}

The component uses this like:

const [thing, setThing] = useLocalStorage('thing', '');

Now, what I want, is to clear this when the component unmounts.

I have tried to clear this with useEffect:

useEffect(() => {
    return () => {
        setThing(prevThing => '');
    }
},[]);

However, this doesn't seem to work. I can even console log in the cleanup
function and see that, but the state change and subsequent clearing of the
localstorage doesn't happen. I'm unsure how to get this to properly clear.

Edit (adding getStorageValue):

const getStorageValue = (key, defaultValue) => {
    let value;
	try {
		const saved = localStorage.getItem(key);
		value = JSON.parse(saved);

	} catch(err) {
		value = false;
	}

	return value || defaultValue;
}

答案1

得分: 1

如果我理解正确,您尝试将值设置为"",期望useEffect回调会响应并将localStorage项目设置为""。然而,由于组件已经正在卸载,设置该值是一个无操作。当这种情况发生时,您应该在控制台看到警告。

幸运的是,您仍然可以从清理回调中访问localStorage,因为这不依赖于组件。

useEffect(() => {
    return () => {
        localStorage.setItem(key, '');
    }
}, [key]);

这个钩子调用将在key更改或组件卸载时将项目设置为""


另外,Storage.setItem(key, '') 不会取消设置键,而是将一个空字符串设置为其值。要取消键,请使用Storage.removeItem(key)

英文:

If I understand correctly you tried to set the value to "" expecting the useEffect callback to run in response and set the localStorage item to "". However, setting the value is a no-op because the component is already unmounting. You should see a warning in the console when this happens.

Luckily you can still access localStorage from a cleanup callback as that doesn't depend on the component.

useEffect(() => {
    return () => {
        localStorage.setItem(key, '');
    }
}, [key]);

This hook invocation will set the item to "" when key changes or the component is unmounted.


As an aside, Storage.setItem(key, '') does not unset the key but rather sets an empty string as its value. To unset a key, use Storage.removeItem(key).

答案2

得分: 0

React组件的本地状态不会知道localStorage。如果您的钩子正在将某些内容设置到本地存储中,那么在卸载时清除它的工作就是钩子的责任,如果需要的话。

它不会自动发生。

英文:

React component's local state won't know anything about the localStorage. If your hook is setting something to local storage, then it's the job of the hook to clear it on unmount if needed.

It won't happen automatically.

huangapple
  • 本文由 发表于 2023年5月22日 05:53:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302066.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定