【问题标题】:React componentDidMount "Parsing error: Missing semicolon"React componentDidMount“解析错误:缺少分号”
【发布时间】:2021-07-21 12:59:41
【问题描述】:

“解析错误:缺少分号”

语法错误:client\src\App.js:缺少分号 (15:21)

componentDidMount() 行显示此错误。

完整代码如下。

import React, { Component } from "react";
import AppNavBar from "./components/AppNavbar";
import ShoppingList from "./components/ShoppingList";
import ItemModal from "./components/ItemModal";
import { Container } from "reactstrap";

import { Provider } from "react-redux";
import store from "./store";
import { loadUser } from "./actions/authActions";

import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";

function App() {
  componentDidMount() {
    store.dispatch(loadUser());
  }
  return (
    <Provider store={store}>
      <div className="App">
        <AppNavBar />
        <Container>
          <ItemModal />
          <ShoppingList />
        </Container>
      </div>
    </Provider>
  );
}

export default App;

【问题讨论】:

  • componentDidMount 用于基于类的 React,您似乎在使用 Hooks,您不能混合使用它们。

标签: javascript node.js reactjs redux react-redux


【解决方案1】:

导入useEffect:

import { useEffect } from "react";

...并替换:

componentDidMount() {
  store.dispatch(loadUser());
}

与:

useEffect(() => {
  store.dispatch(loadUser());
}, []);

【讨论】:

  • useEffect 被调用用于状态更新和初始渲染。所以在某些情况下使用 useEffect 是不明智的。 componentDidMount 仅在状态更新后调用。
猜你喜欢
  • 2021-07-28
  • 1970-01-01
  • 2012-04-26
  • 2018-12-11
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
相关资源
最近更新 更多