React-Redux: Attempted import error: './components/Score' does not contain a default export (imported as 'Score')

React-Redux: Attempted import error: './components/Score' does not contain a default export (imported as 'Score')

我知道有很多类似的帖子,但其中 none 似乎与此相似。

使用react redux 来使用mapStateToProps。

在我的 App.js 中,我使用 import Score from './components/Score'; 来导入组件。

该组件位于名为 Score 的文件夹中,其中包含 index.jsScore.js。在 Score.js 我有:

const Score = ({team_score}) => ( 
    <>  
        <p>{ team_score }</p>
    </>
);

export default Score;

在我的index.js里面我有:

import { connect } from "react-redux";
import Score from "./Score";

let mapStateToProps = (state) => {
    return {
        team_score: state.team_score,
    };
};

connect(mapStateToProps)(Score)

但我得到错误:

./src/App.js
Attempted import error: './components/Score' does not contain a default export (imported as 'Score').

我已经三重检查,文件路径是正确的。我不确定为什么会收到此错误。

我认为你的问题是这个文件夹中有 index.js 文件。

import Score from './components/Score'

此行将尝试从 components/Score/index.js 文件中导入任何内容,而您不会从那里导出任何内容。

您应该执行如下操作:

import { connect } from "react-redux";
import Score from "./Score";

let mapStateToProps = (state) => {
    return {
        team_score: state.team_score,
    };
};

export default connect(mapStateToProps)(Score)

两种解法:

  1. Score 文件夹中的 index.js 文件导出 Score。 (从 Score 文件导入后)
  2. 删除index.js并在App.js
  3. 中使用import Score from './components/Score/Score';

如果您只从模块返回一个值,1更好的组织方式。

错误原因: 您正在从 Score 文件夹导入值。从文件夹导入值时,该文件夹 index.js 中的值 returns。但是这里 index.js 没有导出任何值。因此,要么从 index.js 导出值(解决方案 1),要么从 Score 文件夹中的 Score 文件导入值(解决方案 2)