【问题标题】:Write to a text or JSON file - react - node写入文本或 JSON 文件 - 反应 - 节点
【发布时间】:2021-06-22 08:52:26
【问题描述】:

我指的是post (Write to a text or JSON file in react with node)

我得到了确切的问题,所以我尝试了解决方案。我不太了解解决方案。我花了很多时间通过反复试验来做。例如,在这个解决方案中:

const handleSaveToPC = jsonData => {
  const fileData = JSON.stringify(jsonData);
  const blob = new Blob([fileData], {type: "text/plain"});
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.download = 'filename.json';
  link.href = url;
  link.click();
}

我应该把这段代码放在哪里?变量“handleSaveToPC”已声明但未使用。我应该如何使用它?我在下面展示了我的 App.js 和 index.js 文件。我的目标是将contactsData 数组写入本地json 或文本文件。如果有人准确指导我必须做什么,我将不胜感激。非常感谢。

App.js

import React, { useState, Fragment } from "react";
import AddContactForm from "./forms/AddContactForm";
import EditContactForm from "./forms/EditContactForm";
import ContactTable from "./tables/ContactTable";

const App = () => {

  const contactsData = [
    { id: 1, organization: "A Ltd.", name: "Carol", email: "carol@gmail.com" },
    { id: 2, organization: "B Ltd.", name: "Paul", email: "paul@gmail.com" },
    { id: 3, organization: "C Ltd.", name: "Emily", email: "emily@gmail.com" }
  ];
  
  const initialFormState = { id: null, organization: "", name: "", email: "" };

  const [contacts, setContacts] = useState(contactsData);
  const [currentContact, setCurrentContact] = useState(initialFormState);
  const [editing, setEditing] = useState(false);

  const addContact = (contact) => {
    contact.id = contacts.length + 1;
    setContacts([...contacts, contact]);
  };

  const deleteContact = (id) => {
    setEditing(false);
    setContacts(contacts.filter((contact) => contact.id !== id));
  };

  const editRow = (contact) => {
    setEditing(true);
    setCurrentContact({
      id: contact.id,
      organization: contact.organization,
      name: contact.name,
      email: contact.email
    });
  };

  const updateContact = (id, updatedContact) => {
    setEditing(false);
    setContacts(
      contacts.map((contact) => (contact.id === id ? updatedContact : contact))
    );
  };

  return (
    <div className="container">
      <h1>Address Book</h1>
      <div className="flex-row">
        <div className="flex-large">
          {editing ? (
            <Fragment>
              <h2>Edit contact</h2>
              <EditContactForm
                editing={editing}
                setEditing={setEditing}
                currentContact={currentContact}
                updateContact={updateContact}
              />
            </Fragment>
          ) : (
            <Fragment>
              <h2>Add contact</h2>
              <AddContactForm addContact={addContact} />
            </Fragment>
          )}
        </div>
        <div className="flex-large">
          <h2>View contacts</h2>
          <ContactTable
            contacts={contacts}
            editRow={editRow}
            deleteContact={deleteContact}
          />
        </div>
      </div>
    </div>
  );
};

export default App;

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

【问题讨论】:

    标签: javascript node.js json reactjs


    【解决方案1】:

    编辑:当您尝试通过前端下载文件时,您几乎可以在任何地方使用您的功能。只需添加一个按钮,如下所示:

    &lt;button onClick={handleSaveToPC}&gt;download&lt;/button&gt;

    并将您的功能更改为:

    const handleSaveToPC = () => {
      const fileData = JSON.stringify(contactsData);
      const blob = new Blob([fileData], {type: "text/plain"});
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.download = 'filename.json';
      link.href = url;
      link.click();
    }
    

    原答案:

    我想您将 React 用于前端,将节点用于后端。如果是这样,您可以将数据发送到后端路由,然后使用此功能将数据写入PC。

    我建议使用fs

    这是一个示例函数,您可以如何做到这一点。

    const fs = require('fs')
    
    const writeToJSON = (data) => {
      const DATA_PATH = '/path/to/file'
      fs.writeFile(
        DATA_PATH,
        JSON.stringify(data),
        (err) => {
          if (err) return console.error(err)
          console.log('Wrote data to ', DATA_PATH)
        },
      )
    }

    【讨论】:

    • 我应该在App.js中编写以上代码吗?变量“writeToJSON”已声明但未使用。我应该在哪里使用它?谢谢。
    • 不,fs 仅适用于节点。您是否设置了 axios 或任何 post 方法将信息发送到您的后端?
    猜你喜欢
    • 2019-04-26
    • 1970-01-01
    • 2015-08-26
    • 2021-10-12
    • 2019-08-31
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    相关资源
    最近更新 更多