【问题标题】:How can I Use Consts from different files in React JS如何在 React JS 中使用来自不同文件的 Consts
【发布时间】:2020-07-11 19:50:55
【问题描述】:

你能告诉我如何在 React 中使用来自不同 JS 文件的 const。我正在尝试计算 4 个不同测验分数(平均)的总分。

谢谢!

我确实尝试过导出和导入,但没有成功。

这是我为第一个测验所做的代码:

const playerStatsEco = {
    ecoscore: null,
    numberOfQuestions: null,
    numberOfAnsweredQuestions: null,
    correctAnswers: null,
    wrongAnswers: null,
};

class playeco extends Component {

...

endGame = () => {
        alert('Le quiz est terminé ! لقد انتهى الاختبار');
        const { state } = this;
        playerStatsEco.ecoscore = state.ecoscore;
        playerStatsEco.numberOfQuestions = state.numberOfQuestions;
        playerStatsEco.numberOfAnsweredQuestions = state.correctAnswers + state.wrongAnswers;
        playerStatsEco.correctAnswers = state.correctAnswers;
        playerStatsEco.wrongAnswers = state.wrongAnswers;
    
    setTimeout(() => {
        this.props.history.push('/play/sum', playerStatsEco);
    }, 1000);
};

当我尝试导出类时,它可以工作。但是当我尝试使用这一行导出 const 时

export  {playeco, playerStatsEco};

发生此错误:

尝试导入错误:“./components/quiz/playeco”不包含默认导出(导入为“playeco”)。

【问题讨论】:

  • 只要用export把它们导出,再导入到你想用的文件里…………
  • @SR810 感谢您的回答,但是当我尝试使用用于路由器的主类导出它时(export {playeco, playStatsEco};)它向我显示一个错误:“尝试导入错误: './components/quiz/playeco' 不包含默认导出(导入为 'playeco')。”
  • 与其问一般的“我该怎么做”问题,不如在问题内容中显示导致问题的代码以及错误消息。所有人都可以轻松格式化和阅读。您可以随时编辑问题以添加此类说明。还要花点时间阅读How to Askminimal reproducible example
  • 好多了。这就是它在这里的工作方式......向我们展示实际的代码问题。虽然没有显示任何导出或导入语句
  • @charlietfl 我刚刚添加了错误

标签: javascript node.js reactjs


【解决方案1】:

您可以导出常量并从不同的文件中导入它们。

 // In file where constant declared
 export const myConst = "some value";

 //In imported file
 import {myConst} from "./fileWhereConstDeclared"

【讨论】:

  • 感谢您的回答。在这种情况下,我怎样才能导出存在于同一文件中的类呢?我试过了: export {myClass, myConst};但没用
【解决方案2】:

您可以导出它们:

export const playerStatsEco = {...}

export class playeco extends Component {...}

然后你可以像这样从外部导入它们:

 import {playerStatsEco, playeco } from "./fileWhereConstDeclared"

【讨论】:

    猜你喜欢
    • 2019-08-18
    • 2013-12-30
    • 2018-05-31
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2012-12-26
    • 2012-08-16
    相关资源
    最近更新 更多