【问题标题】:How can I write to a file from a React component?如何从 React 组件写入文件?
【发布时间】:2022-01-14 06:10:37
【问题描述】:

我有一个 SideNav 菜单,用于查找名为 route.js 的文件,其中包含一个名为 routes 的数组。我正在尝试从另一个组件更改 routes.js 中路由的值。我希望能够从组件中添加删除文件 routes.js 中的物理数组。任何帮助将不胜感激。

import Shop from "examples/Icons/Shop";
// import Office from "examples/Icons/Office";

const routes = [
  {
    type: "collapse",
    name: "Our Mission",
    key: "dashboards",
    icon: <Shop size="12px" />,
    collapse: [
      {
        name: "Ways We can Help",
        key: "default",
        route: "/dashboards/default",
        component: Default,
      },
      {
        name: "How It Works",
        key: "automotive",
        route: "/dashboards/automotive",
        component: Automotive,
      },
      {
        name: "Who We Are",
        key: "smart-home",
        route: "/dashboards/smart-home",
        component: SmartHome,
      },
    ],
  },
  { type: "title", title: " ", key: "space1" },
  {
    type: "collapse",
    name: "Services",
    key: "services",
    icon: <Shop size="12px" />,
    href: "https://github.com/creativetimofficial/ct-soft-ui-dashboard-pro-material-ui/blob/main/CHANGELOG.md",
    component: Default,
    noCollapse: true,
  },
];
export default routes;

组件访问 routes.js

import routes from "../../../routes";
const loggedroutes = [
  {
    type: "collapse",
    name: "Profile",
    key: "profile",
    icon: <CgProfile size="12px" color="blue" />,
    route: "/dashboards/Default",
    collapse: [],
  },
  {
    type: "collapse",
    name: "Calendar",
    key: "calendar",
    component: link,
    route: "/dashboards/Default",
    icon: <GoCalendar size="12px" color="blue" />,
    collapse: [],
  },
]

routes = loggedinroutes;

我想更改 routes.js 中的数据以匹配数组 loggedinroutes

【问题讨论】:

  • 什么是“物理阵列”?
  • 您是说要写入文件吗?这与更新内存中的数组不同。
  • 我要写入文件

标签: node.js arrays reactjs jsx


【解决方案1】:

好吧,在不知道你在做什么的情况下,我整理了一个快速沙盒来说明我将如何去做。

https://codesandbox.io/s/hopeful-shirley-q9mhz?file=/src/routes.js

我基本上会使用基于按钮单击/状态/页面查询/等的逻辑,并将其传递给一个函数,该函数将动态加载导航栏中的路由。在 app.js 文件中,您可以看到我如何使用 useState() 挂钩和按钮单击来动态加载路由。

我确信有一种更优雅的方式来实现这一点,但我希望这能让你朝着正确的方向前进!

【讨论】:

  • 意思是我想保存一个位于 routes.js 文件中的数组。不仅是状态,还有实际的文件。
  • 德里克,请看How to Answer。 SO 上没有足够的解决方案链接。
  • 感谢您的回复。我有 routes.js 存储用于填充菜单的 json 数组。我想从组件中的 routes.js 加载数组,并能够将数组保存回 routes.js。我不想加载和保存数组状态。我想实际从 jsx 写入文件,将数组保存回 routes.js 文件。
  • 也许有人可以参与进来,但我不相信你可以在编译后物理写入 jsx 文件。您需要执行我在代码示例中显示的操作,或者您可以将数据写入数据库/本地存储/cookie 或我没有想到的其他类型的缓存,然后从您的代码中调用它,但我'不清楚为什么你需要为菜单这样做?
猜你喜欢
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
相关资源
最近更新 更多