在函数元素类型中反应useState钩子无效

时间:2019-10-14 20:03:04

标签: reactjs react-hooks

我有一个应用程序,尝试从异步函数内部使用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;

1 个答案:

答案 0 :(得分:0)

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