【问题标题】:Why is my export const function not importing properly?为什么我的 export const 函数没有正确导入?
【发布时间】:2019-04-16 13:11:30
【问题描述】:

所以我正在创建一个简单的反应应用程序,它导出一个文件,其中包含一个返回对象数组的函数:

export const listStudents = () => {
    return [{name:"Ljuben", lastName:"Angelkoski", indeks:"161161", nasoka:"KNI"},
            {name:"Pere", lastName:"Anastasov", indeks:"17350", nasoka:"PET"},
            {name:"Filip", lastName:"Shabanoski", indeks:"173521", nasoka:"PET"},
            {name:"Martin", lastName:"Krsteski", indeks:"163544", nasoka:"KNI"},
            {name:"Nikola", lastName:"Nacevski", indeks:"154874", nasoka:"ASI"}]; // replace the empty array with actual array with at least 5 student objects
}

在我的主要组件中,我有以下代码:

import React, {Component} from 'react'
import listStudents from './repository/studentRepository.js'

class Main extends Component{
    constructor(props){
        super(props);

        this.state={
            students: listStudents
        }
    }

    render(){
        return (
            <h2></h2>
        )
    }
}

export default Main

但是,当我运行该应用程序时,它给了我这个错误:

./src/Main.js
Attempted import error: './repository/studentRepository.js' does not contain a default export (imported as 'listStudents').

有什么想法吗?

【问题讨论】:

  • 编辑:你需要正确import你的studentRepository.js
  • 还将 this.state={ students: listStudents } 更改为 this.state={ students: listStudents() }
  • 任何答案对您有用吗?如果是这种情况,请考虑 accepting one of them

标签: reactjs


【解决方案1】:

listStudents 是一个命名导出,所以你必须像这样导入它:

import { listStudents } from './repository/studentRepository.js'

如果您不想更改导入,可以使用函数的默认导出。

export default () => {
    return [/* ... */]; 
}

【讨论】:

    【解决方案2】:

    如果children.js 中没有提及默认导出,则需要使用名称导入。

    import { liststudents } from './children';
    

    或者你必须提到像孩子一样的默认导出

    export default const list = []
    

    它也是children.js 中的一个函数。所以要从中获取数据,您需要像这样调用它。

     this.state = {
        students: listStudents()
     }
    

    更简单的方法是将它们定义为像

    这样的数组
    export const listStudents = [...students arr]
    

    【讨论】:

      猜你喜欢
      • 2015-08-30
      • 2019-03-12
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 2021-05-19
      • 2011-10-19
      • 2015-03-21
      • 1970-01-01
      相关资源
      最近更新 更多