元素类型无效:期望为字符串或类/函数,但得到了:对象。

时间:2018-12-09 13:13:47

标签: spring reactjs spring-boot webpack

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

因此,我在我的应用程序中将react js与spring boot一起使用。我已经成功配置了webpack(我认为),但是我遇到的问题是HTML页面加载后,它没有在“ div”标签中呈现任何内容。 :(

App.js

import {React} from 'react';
import {ReactDOM} from 'react-dom';
const client = require('./client');

//import css from "./App.css";
import {NavBar} from './navbar';
import {Home} from './home';
//const index = require('/alpha/src/main/resources/templates/index.html');


const heroImageStyling = {
          height: 200,
          width: 200
        };

class App extends React.Component {
  state = {
    products: [
      { id: 1, value: 0, name: "Item 1" },
      { id: 2, value: 0, name: "Item 2" },
      { id: 3, value: 0, name: "Item 3" },
      { id: 4, value: 0, name: "Item 3" },
      { id: 5, value: 0, name: "Item 3" },
      { id: 6, value: 0, name: "Item 4" },
      { id: 7, value: 0, name: "Item 4" },
      { id: 8, value: 0, name: "Item 5" }
    ]
  };


  constructor(props) {
        super(props);
        this.state = {products: []};
    }

   componentDidMount() {
     client({ method: "GET", path: "/" }).done(response => {
       this.setState({ products: response.entity._embedded.products });
     });
   }
  handleDelete = id => {
    console.log("event handled", id);
  };

  handleNavBarCartIncrement = product => {
    const products = [...this.state.products];
    const index = products.indexOf(product);
    products[index] = { ...product };
    products[index].value++;
    this.setState({ products });

    console.log(product);
  };

  render() {
    return (
            <React.Fragment>
            <NavBar
              cartItems={this.state.products.filter(c => c.value > 0).length}
            />
            <main className="container">
              <Home
                products={this.state.products}
                onIncrement={this.handleNavBarCartIncrement}
                onDelete={this.handleDelete}
              />
            </main>
          </React.Fragment>
                );
              }

}

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

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8"/>
    <title>ReactJS + Spring Data REST</title>
    <link rel="stylesheet" href="/main.css" />
</head>
<body>

    <div id="react"></div>

    <script src="/built/bundle.js"></script>

</body>
</html>

我的index.html曾经用于获取react组件,但除了没有标签的标签外,没有显示其他任何内容。但是,它也不这样做。现在,它不检索任何内容,而是出现以下错误。

1 个答案:

答案 0 :(得分:0)

您必须导入没有大括号的React,ReactDom和您的类。

如果您使用导出默认值来导出文件,则无需放置花括号,如果仅使用导出,则必须使用{}

另一件事是,如果您不想自己配置webpack和bable,则可以使用create-react-app命令创建一个新的react项目,所有项目都将为您设置。

命令为: npx create-react-app myApp