首页 > 解决方案 > 如何存储/检索包含获取新数据的函数的 JSON 对象?

问题描述

const Data = {
    teachers: {
        size: 15,
        num: 4,
        color: 'blue'
    }
}

const person = {
    name: 'John',
    group: Data.teachers, // This is Default. If I do this, the entire teachers tree gets cached. Later, teachers tree changes, this is unusable.
    group: () => Data.teachers // I want to do this, so that it fetches fresh data. But, see below for the LJSON problem...
}

我了解 JSON.stringify 不支持函数。

我研究了 LJSON ( https://github.com/MaiaVictor/LJSON )。LJSON 不能解决问题。它们还按原样缓存 Data.teacher。使用 LJSON 时,如果Data.teachers发生变化,则调用group()不会得到最新的。它将返回老树。

(当前堆栈是 React-Native,带有 AsyncStorage,使用 JSON.stringify/parse。)

标签: javascriptjsonreact-nativecachingserialization

解决方案


您是否尝试过&的toString()方法?Functioneval

const fn = (arg) => {
  console.log('function:', arg)
}
fn('yes, it works')

const jsonFn = JSON.stringify(fn.toString()) // now its a JSON.stringified string
const newJsonFn = JSON.parse(jsonFn) // parsing it back from JSON to string
const newFn = eval(newJsonFn) // eval!!!
newFn('yes, it works again')

重要的

是的,这个片段解决了你的问题。但不要忘记这eval是一个危险的工具:关于 eval 安全问题


推荐阅读