反应 - 错误:尝试导入错误/应用程序'不包含默认导出(导入为'应用程序'

Oma*_*mar 4 reactjs react-hooks

返回错误:./src/index.js 尝试导入错误:“./App”不包含默认导出(作为“App”导入)。

import React, { Component, useState } from "react";

const App = () => {
    const [count, setCount] = useState(0);

  const  increment = () => {
        setCount(count + 1);
    };

    return (
      <div>
          <h2> counter app </h2>
          <button onClick={increment}>Clicked {count} times</button>
      </div>
    );
};
Run Code Online (Sandbox Code Playgroud)

指数

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';


ReactDOM.render(<App />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)

jdn*_*jdn 10

在 Nodejs 中,要在另一个文件中使用变量或函数,您必须导出它们。我们有两种类型的出口。

1. 使用导出常量

// Export a variable
export const App = () => { ... }

// Import App in another file
import { App } from '...'
Run Code Online (Sandbox Code Playgroud)

2. 使用导出默认值

// Export default
const App = () => { ... }
export default App

// Import App in another file
import App from '...'
Run Code Online (Sandbox Code Playgroud)

按照我的示例并查看您的代码。您缺少导出App到可以在另一个文件中使用此变量。

因此,在您的情况下,您必须导出App才能使用index.js

import React, { Component, useState } from "react";

const App = () => {
    const [count, setCount] = useState(0);

  const  increment = () => {
        setCount(count + 1);
    };

    return (
      <div>
          <h2> counter app </h2>
          <button onClick={increment}>Clicked {count} times</button>
      </div>
    );
};
export default App
Run Code Online (Sandbox Code Playgroud)

请记住,一个文件中只有一个导出默认值。