是否可以从React函数中仅导出一个常量变量?

时间:2019-09-16 08:38:45

标签: javascript reactjs react-hooks

我正在尝试使用API​​调用设置对象的值,并将结果从我的应用程序内部导出到其他类。

这就是我要尝试的方式

import {MaterialUIComponentsNavigation} from 'app/main/documentation/material-ui-components/MaterialUIComponentsNavigation';
import {authRoles} from 'app/auth';
import {callTextApi} from "../services/textService/textContext";
import {useState} from "react";

function navigationConfig () {

  console.log("Random");
  return test =  [
    {
      'id'      : 'applications',
      'title'   : 'Applications',
      'type'    : 'group',
      'icon'    : 'apps',
      'children': [
        {
          'id'      : 'dashboards',
          'title'   : 'Dashboards',
          'type'    : 'collapse',
          'icon'    : 'dashboard',
          'children': [
            {
              'id'   : 'analytics-dashboard',
              'title': 'Raaaaaaaaaaaa',
              'type' : 'item',
              'url'  : '/apps/dashboards/analytics'
            },
            {
              'id'   : 'project-dashboard',
              'title': 'Project',
              'type' : 'item',
              'url'  : '/apps/dashboards/project'
            }
          ]
        },
//some more object fields
}
export default navigationConfig;

我的问题是:有没有办法只导出测试变量而不导出整个函数? 我需要将此作为函数,因为我不能在常量内部使用react钩子,这就是为什么我试图从函数内部导出常量。

导出看起来像这样

navigationConfig() {
  console.log("Random");
  return test = [{
    'id': 'applications',
    'title': 'Applications',
    'type': 'group',
    'icon': 'apps',
    'children': [{
      'id': 'dashbo…

看起来应该像这样:

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: "authentication", title: "Authentication", type: "collapse", icon: "lock", badge: {…}, …}
1: {id: "coming-soon", title: "Coming Soon", type: "item", icon: "alarm", url: "/pages/coming-soon"}
2: {id: "errors", title: "Errors", type: "collapse", icon: "error", children: Array(2)}
3: {id: "invoice", title: "Invoice", type: "collapse", icon: "receipt", children: Array(2)}
4: {id: "maintenance", title: "Maintenance", type: "item", icon: "build", url: "/pages/maintenance"}
5: {id: "pricing", title: "Pricing", type: "collapse", icon: "attach_money", children: Array(3)}
6: {id: "profile", title: "Profile", type: "item", icon: "person", url: "/pages/profile"}
7: {id: "search", title: "Search", type: "collapse", icon: "search", children: Array(2)}
8: {id: "faq", title: "Faq", type: "item", icon: "help", url: "/pages/faq"}
9: {id: "knowledge-base", title: "Knowledge Base", type: "item", icon: "import_contacts", url: "/pages/knowledge-base"}

希望问题能解决这个问题。

P.S。我还在学习React,所以请不要太苛刻:D

2 个答案:

答案 0 :(得分:1)

您可以像这样导出变量:

const data = {};

export default data;

答案 1 :(得分:0)

您可以仅导出函数并在需要的地方调用它。不知道我是否正确理解了您的问题。

如果您仍要导出对象而不是函数,则可以执行以下操作:

navigationConfig() {
    // ....
}

const myExport = navigationConfig();

export default myExport;