React.js-无法将简单变量从一个文件导入另一个文件

时间:2020-08-30 09:38:13

标签: javascript reactjs

我无法弄清楚如何将一个非常简单的变量从一个文件导入另一个文件(新的响应)。我有主App.js,其中第3行似乎是问题所在:

import React, {Component} from "react";
import NavMenu from "./components/nav-menu";
import navLinks from "/components/nav-links";

export default class App extends Component {
  constructor() {
    super();

    this.state = {
      navLinks: navLinks
    }
  }

  render() {
    return (
      <div id="container">
        <NavMenu navLinks={this.state.navLinks} />
      </div>
    );
  } 
}

仅从此navLinks文件中导入(或应导入)nav-links.js变量:

import React from 'react';

export const navLinks = [
    {
      name: "home",
      href: "/"
    },
    {
      name: "subs",
      href: "/subs"
    }
  ];

有人可以指出我在哪里出问题的正确方向吗?另外,它仅用于呈现导航菜单(因此标记内的链接)-通常这是添加导航链接的正确方法吗?

Stackblitz:https://stackblitz.com/edit/react-j42gep

2 个答案:

答案 0 :(得分:1)

您没有将导航链接默认导出:

import React from 'react';

 const navLinks = [
    {
      name: "home",
      href: "/"
    },
    {
      name: "subs",
      href: "/subs"
    }
  ];

  export default navLinks;

并在.中添加点import navLinks from "./components/nav-links";

答案 1 :(得分:1)

如果您正在这样做:

export const navLinks = [
    {
      name: "home",
      href: "/"
    },
    {
      name: "subs",
      href: "/subs"
    }
  ];

然后您将其导入错误。然后执行以下操作:

import {navLinks} from "./components/nav-links";

注意./components/nav-links您在导入语句中忘记了./

如果您不想使用{},请在导出中添加如下的默认语句:

const navLinks = [
    {
      name: "home",
      href: "/"
    },
    {
      name: "subs",
      href: "/subs"
    }
  ];

  export default navLinks;