手写 useLocalStorage 时发现的问题?-灵析社区

你好我叫张倩话

/** * 获取浏览器 localStorage 中的值, 也可对该值进行更新操作 * * @param {String} key---localStorage中存储的键值对的key * @return {String} value---localStorage中存储的键值对的value * @return {Function} setValue---更新方法,可对localStorage中存储的键值对进行更新操作,本方法接受一个参数,该参数为更新后的值 * * @example * const { value: nameValue, setValue: setNameValue } = useLocalStorage('name') * console.log(nameValue) * setNameValue('uni-app') * console.log(nameValue) */ function useLocalStorage(key) { // 生成一个代理对象 const ref = {} Object.defineProperty(ref, key, { get() { const storage = JSON.parse(localStorage.getItem(key) ?? '') return storage }, }) function setValue(newVal) { localStorage.setItem(key, JSON.stringify(newVal)) } return { get value() { return ref[key] }, setValue, } } localStorage.setItem('name', JSON.stringify('uni-app')) const { value: nameValue, setValue: setNameValue } = useLocalStorage('name') console.log(nameValue) // 'uni-app' setNameValue('JavaScript') console.log(nameValue) // 这里输出的不是 'JavaScript', 仍然是 'uni-app' 问题就是代码段最后一个输出,不知道为什么还是 "uni-app"

阅读量:13

点赞量:0

问AI
const { value: nameValue, setValue: setNameValue } = useLocalStorage('name') nameValue是基本类型,而不是引用类型,自然还是'uni-app'