【问题标题】:React useState hook inside function Element type invalid反应函数内的useState钩子元素类型无效
【发布时间】:2020-02-11 11:14:06
【问题描述】:

我有一个应用程序在尝试从异步函数内部使用 useState 挂钩时出错。

这里是 App.js

import React, { useState, useEffect } from "react";
import { Auth } from "aws-amplify";
import { Link, withRouter } from "react-router-dom";
import { Nav, Navbar} from "react-bootstrap";
import { LinkContainer } from "react-router-bootstrap";
import Routes from "./Routes";


function App(props) {
  const [isAuthenticating, setIsAuthenticating] = useState(true);
  const [isAuthenticated, userHasAuthenticated] = useState(false);

  useEffect(() => {
    onLoad();
  }, []);

  async function onLoad() {
    try {
      await Auth.currentSession();
      userHasAuthenticated(true);
    }
    catch(e) {
      if (e !== 'No current user') {
        alert(e);
      }
    }
    setIsAuthenticating(false);  <-------- errors

  }

  async function handleLogout() {
    await Auth.signOut();

    userHasAuthenticated(false);

    props.history.push("/login");
  }

  return (
    !isAuthenticating && (
      <div>
        <Navbar fluid collapseOnSelect>
          <Navbar.Header>
            <Navbar.Brand>
              <Link to="/">Spaced - In</Link>
            </Navbar.Brand>
            <Navbar.Toggle />
          </Navbar.Header>
          <Navbar.Collapse>
            <Nav pullRight>
              {isAuthenticated ? (
                <>
                  <LinkContainer to="/settings">
                    <Nav.Link>Settings</Nav.Link>
                  </LinkContainer>
                  <Nav.Link onClick={handleLogout}>Logout</Nav.Link>
                </>
              ) : (
                <>
                  <LinkContainer to="/signup">
                    <Nav.Link>Signup</Nav.Link>
                  </LinkContainer>
                  <LinkContainer to="/login">
                    <Nav.Link>Login</Nav.Link>
                  </LinkContainer>
                </>
              )}
            </Nav>
          </Navbar.Collapse>
        </Navbar>
        <Routes appProps={{ isAuthenticated, userHasAuthenticated }} />
      </div>
    )
  );
}

export default withRouter(App);

这是错误

元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

查看App的渲染方法。

onLoad
src/App.js:28

  25 |       alert(e);
  26 |     }
  27 |   }
> 28 |   setIsAuthenticating(false);
     | ^  29 |  
  30 | }
  31 | 

index.js

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";
import "./index.css";
import Amplify from "aws-amplify";
import 'bootstrap/dist/css/bootstrap.min.css';
import config from "./config";

Amplify.configure({
  Auth: {
    mandatorySignIn: true,
    region: config.cognito.REGION,
    userPoolId: config.cognito.USER_POOL_ID,
    identityPoolId: config.cognito.IDENTITY_POOL_ID,
    userPoolWebClientId: config.cognito.APP_CLIENT_ID
  }
,
  Storage: {
    region: config.s3.REGION,
    bucket: config.s3.BUCKET,
    identityPoolId: config.cognito.IDENTITY_POOL_ID
  },
  API: {
    endpoints: [
      {
        name: "spaces",
        endpoint: config.apiGateway.URL,
        region: config.apiGateway.REGION
      },
    ]
  }
});

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  document.getElementById("root")
);
registerServiceWorker();

package.json

{
  "name": "spaced-in",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "aws-amplify": "^1.2.2",
    "bootstrap": "4",
    "react": "^16.10.2",
    "react-bootstrap": "^1.0.0-beta.14",
    "react-dom": "^16.10.2",
    "react-router-bootstrap": "^0.25.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

更新错误 - 从 App.js 的返回中删除 !isAuthenticating &&

元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

检查App的渲染方法。

./src/index.js
src/index.js:36

  33 |   }
  34 | });
  35 | 
> 36 | ReactDOM.render(
  37 |   <Router>
  38 |     <App />
  39 |   </Router>,

__webpack_require__
/home/geekylumberjack/Desktop/spaced-in/webpack/bootstrap:785

  782 | };
  783 | 
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  786 | 
  787 | // Flag the module as loaded
  788 | module.l = true;

fn
/home/geekylumberjack/Desktop/spaced-in/webpack/bootstrap:150

  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {

0
http://localhost:3000/static/js/main.chunk.js:1515:18
__webpack_require__
/home/geekylumberjack/Desktop/spaced-in/webpack/bootstrap:785

  782 | };
  783 | 
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  786 | 
  787 | // Flag the module as loaded
  788 | module.l = true;

checkDeferredModules
/home/geekylumberjack/Desktop/spaced-in/webpack/bootstrap:45

  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 | 

webpackJsonpCallback
/home/geekylumberjack/Desktop/spaced-in/webpack/bootstrap:32

  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 | 
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;

【问题讨论】:

  • 那里发生错误是没有意义的。你的App函数组件的返回值是多少?
  • 这个错误只是误导。您没有错误地导出/导入模块。上面的sn-p很难说
  • 我添加了更多代码。请让我知道是否还有其他帮助
  • 乍一看,当isAuthenticatingtrue 时,您的应用程序在!isAuthenticating &amp;&amp; (&lt;div&gt;... 中返回undefined,而React 无法呈现它。虽然如果是这样的话,那么我不确定为什么会在第 28 行报告错误。
  • 可能是因为 setAuthenticating(false) 触发了返回 false 而不是元素的重新渲染。试着用类似isAuthenticating ? &lt;&gt;Authenticating...&lt;/&gt; : (&lt;div&gt;...的东西替换!isAuthenticating &amp;&amp; (&lt;div&gt;...

标签: reactjs react-hooks


【解决方案1】:

如果其他人遇到此问题,似乎如果您在任何返回的函数中有不正确的内容,它将在索引或 setIsAuthenticating(false) 处出错。

【讨论】:

    猜你喜欢
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多