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

时间:2019-11-05 02:44:53

标签: 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>
    );
};

索引

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


ReactDOM.render(<App />, document.getElementById('root'));

3 个答案:

答案 0 :(得分:1)

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

  1. 使用导出常量
// Export a variable
export const App = () => { ... }

// Import App in another file
import { App } from '...'
  1. 使用导出默认值
// Export default
const App = () => { ... }
export default App

// Import App in another file
import App from '...'

按照我的示例查看您的代码。您缺少导出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

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

答案 1 :(得分:0)

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;

答案 2 :(得分:0)

import openSocket from 'socket.io-client';

class Socket {
  constructor() {
    this.socket = openSocket('http://localhost:8080');
    this.socket.emit("connection", 1000);
  }
}

export default new Socket();


import socketService  from "../../services/socketService";

socketService.socket.on("new-order", (result) => {
  if (result.data) {
    console.log('order page',result.data);
    let x = [...records];
    x.unshift(result.data);
    setRecords(x);
  }
});