【问题标题】:Storing an Array of React.js Elements in Javascript to some File or any Storage so it Could be Used Later将 Javascript 中的 React.js 元素数组存储到某个文件或任何存储中,以便以后使用
【发布时间】:2021-01-17 18:54:22
【问题描述】:

注意:我不能使用 Node FS 模块,因为我对 npm 和 fs 了解不多。

我正在创建一个小型虚拟游戏,用户可以单击一个按钮在屏幕上获得一个“鸭子”,这只是一个 <img>,但所有这些都是在 React.js 中完成的。我有一个数组duckMem,它存储由React 通过createElement 调用创建的元素。代码如下所示:

var duckMem = [];
var e = React.createElement('img',{src:'src'},null};
duckMem.push(e);
ReactDom.render(...);

我现在想保存游戏的状态,即当前屏幕上的鸭子。当用户关闭并打开 Local HTML 文件时,所有的鸭子都应该在那里。

我尝试了什么:

saveByteArray(duckMem, "duck.txt");
var saveByteArray = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, name) {
        var blob = new Blob(data, {type:"application/octet-stream" /*"octet/stream"*/}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

和

一个示例here,我对其进行了一些修改,以便在窗口关闭事件时下载 txt 文件。

到目前为止我取得了什么成就:

我能够得到一个包含以下内容的文件:

[object Object], [object Object], [object Object]

这是一个对应于duckMem的对象数组。

typeof React.createElement

也评估为Object。

我想做什么:

我使用了一个文本文件,所以我可以很容易地看到文件中的数据(如果它是随机或非 ASCII 字符,那么数据已经成功写入,我认为)否则可以使用任何文件扩展名。

我会创建一个包含二进制数据的文件,当用户打开 HTML 文件时,读取该二进制数据并渲染所有鸭子以恢复保存的状态。

【问题讨论】:

    标签: javascript reactjs file


    【解决方案1】:

    我不确定您是否以正确的方式进行此操作。 React.createElement() 的输出是否实际上是可序列化的(也可以表示为字符串)我目前还不清楚。

    但有一件事是肯定的: 如果是您要保存的状态,请在文件中写入实际的src 属性。 duck.txt 只会列出鸭子的 URL。 这有一些优点:对于初学者来说,它使该文件更易于维护。 而且,这个 URL 列表可以成为一个状态条目,强制组件在它(列表)更改时重新呈现。

    当你需要恢复状态时

    // Read the URLs from the file.
    // We expect ducks to be an array of strings.
    // We will pass this array to the React Component that renders the ducks.
    const ducks = readFromFile("duck.txt");
    
    
    // Function that renders the ducks.
    // It receives a list of ducks URLs as props
    function DucksRenderer(ducksURLArray) {
    
      return (
        <div className="ducks-container">
          {
             ducks.map(duckURL => <img src={duckURL}/>)
          }
        </div>
      );
    }
    

    注意:您似乎是在浏览器中执行此操作,保存此数据的更好方法是使用LocalStorage。

    // To write the list of ducks urls
    localStorage.setItem('ducksURLs', JSON.stringify(ducks));
    
    // To read the list
    const ducksURLs = JSON.parse(localStorage.getItem('ducksURLs'));
    

    【讨论】:

    • 我很感激@KibongeMurphy。我所有的搜索都集中在创建文件上,从未偶然发现 localStorage。我写了大约 80 行来编写一个文件并读取它,但现在我有一个 3 行。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-02-09
    • 2011-10-28
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    相关资源
    最近更新 更多