简体   繁体   English

将 Function 作为道具传递时,React.js -“不是函数”或“渲染未返回任何内容”错误

[英]React.js - 'is not a function' Or 'Nothing was returned from render' Error when passing a Function as prop

I am new to React and building a CRUD operation react-app for practice.我是 React 的新手,并为练习构建了一个 CRUD 操作 react-app。 I have 2 files(one is Login.js and another is RequireAuth.js) which are inside same folder/directory(components).我有 2 个文件(一个是 Login.js,另一个是 RequireAuth.js),它们位于同一个文件夹/目录(组件)中。 I have function of user authenticate in Login.js file which I'm calling/running on onClick of login button.我在 Login.js 文件中有用户身份验证的 function,我在登录按钮的 onClick 上调用/运行该文件。

And in my second file(RequireAuth.js) I am setting private routing that only authenticated user is allowed to go on the paths like /home, /profile etc. and If the user is not authenticated, then he/she can only go to /login and /signup.在我的第二个文件(RequireAuth.js)中,我设置了私有路由,只允许经过身份验证的用户在 /home、/profile 等路径上使用 go,如果用户未通过身份验证,那么他/她只能 go 到/登录和/注册。

Now I want to call/access the function of user authenticate(which I'm calling/running on onClick of login button in the Login.js file) in this private routing(RequireAuth) file.现在我想在这个私有路由(RequireAuth)文件中调用/访问用户身份验证的 function(我在 Login.js 文件中的登录按钮的 onClick 上调用/运行)。 I tried to pass the function of user authenticate(from Login.js) as a prop in RequireAuth.js file but I am not getting the desired result.我尝试将用户身份验证(来自 Login.js)的 function 作为 RequireAuth.js 文件中的道具传递,但我没有得到想要的结果。

Basically I am getting 2 errors right now and both my errors are coming in the RequireAuth.js file itself.基本上我现在收到 2 个错误,而且我的两个错误都出现在 RequireAuth.js 文件本身中。 I am going to tell the errors in details like this that I am getting from my existing code.我将详细说明我从现有代码中得到的错误。

A) When I set AuthenticateUser to AuthenticateUser() in RequireAuth function(as I have shown below) in RequireAuth.js so I get an error that Uncaught TypeError: AuthenticateUser is not a function . A)当我在 RequireAuth.js 中的 RequireAuth 函数(如下所示)中将 AuthenticateUser 设置为 AuthenticateUser() 时,我收到一个错误,即Uncaught TypeError: AuthenticateUser is not a function

import React from "react";
import { Navigate } from "react-router-dom";

const RequireAuth = ({ AuthenticateUser }) => {
  AuthenticateUser = true;
  let auth = AuthenticateUser();
  return !auth ? <Navigate to="/" /> : /*<Navigate to="/home" />, <Navigate to="/profile" /> etc. etc.*/;
};
export default RequireAuth;

B) and When I don't make any changes to RequireAuth.js file(as i have shown below again) and leave it as it is, I get the error Uncaught TypeError: RequireAuth(...): Nothing was returned from render. B)并且当我不对 RequireAuth.js 文件进行任何更改(如下所示)并保持原样时,我收到错误Uncaught TypeError: RequireAuth(...): Nothing was returned from render . This usually means a return statement is missing.这通常意味着缺少 return 语句。 Or, to render nothing, return null .或者,不渲染任何内容,返回 null

import React from "react";
import { Navigate } from "react-router-dom";

const RequireAuth = ({ AuthenticateUser }) => {
  AuthenticateUser = true;
  let auth = AuthenticateUser;
  return !auth ? <Navigate to="/" /> : /*<Navigate to="/home" />, <Navigate to="/profile" /> etc. etc.*/;
};
export default RequireAuth;

Here I don't know what I'm doing wrong or missing in my code.在这里,我不知道我的代码做错了什么或遗漏了什么。 All files of my code are as below:我的代码的所有文件如下:

Login.js登录.js

import React, { useState } from "react";
import { Form, Button } from "react-bootstrap";
import RequireAuth from "./RequireAuth";

const Login = () => {
  const initialValues = {
    email: "",
    password: "",
  };

  const [userData, setUserData] = useState(initialValues);
  const AuthenticateUser = () => {
    const localInfo = JSON.parse(localStorage.getItem("signUpUser"));
    if (localInfo === null) {
      alert("No user exist");
      return false;
    } else {
      localInfo?.map((item) => {
        const userName = item.email;
        const userPassword = item.password;
        if (userName === userData.email && userPassword === userData.password) {
          alert("Login Successfully.");
        } else {
          alert("Login Failed.");
          return false;
        }
      });
      setUserData(initialValues);
    }
  };

  return (
    <>
      <Form className="loginForm">
        <Form.Group className="mb-3" controlId="formBasicEmail">
          <Form.Label>Email Address</Form.Label>
          <Form.Control
            type="email"
            placeholder="Enter email"
            value={userData.email}
            name="email"
            onChange={(e) =>
              setUserData({ ...userData, [e.target.name]: e.target.value })
            }
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control
            type="password"
            placeholder="Password"
            name="password"
            value={userData.password}
            onChange={(e) =>
              setUserData({ ...userData, [e.target.name]: e.target.value })
            }
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="formBasicCheckbox"></Form.Group>

        <Button
          variant="primary"
          type="submit"
          onClick={() => AuthenticateUser()}
        >
          Login
        </Button>
      </Form>
      {false ? <RequireAuth AuthenticateUser={AuthenticateUser} /> : ""}
    </>
  );
};
export default Login;

RequireAuth.js RequireAuth.js

import React from "react";
import { Navigate } from "react-router-dom";

const RequireAuth = ({ AuthenticateUser }) => {
  AuthenticateUser = true;
  let auth = AuthenticateUser;
  return !auth ? <Navigate to="/" /> : /*<Navigate to="/home" />, <Navigate to="/profile" /> etc. etc.*/;
};
export default RequireAuth;

App.js应用程序.js

import React from "react";
import "./App.css";
import Profile from "./Profile";
import Login from "./Login";
import SignUp from "./SignUp";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./Home";
import RequireAuth from "./RequireAuth";

const App = () => {
  return (
    <>
      <Router>
        <Routes>
          <Route exact path="/" element={<Login />} />
          <Route exact path="/signUp" element={<SignUp />} />
          <Route
            exact
            path="/home"
            element={
              <RequireAuth>
                <Home />
              </RequireAuth>
            }
          />
          <Route exact path="/profile" element={<Profile />} />
        </Routes>
      </Router>
    </>
  );
};

export default App;

Please help me.请帮我。 I thank you all in advance.我提前感谢大家。

You're reassigning the AuthenticateUser prop, which was passed as a function, to a boolean when the component mounts (when your component function is called by React).当组件安装时(当 React 调用组件 ZC1C425268E68385D1AB5074C17A94F14 时),您将作为 function 传递的AuthenticateUser属性重新分配给 boolean。

import React from "react";
import { Navigate } from "react-router-dom";

const RequireAuth = ({ AuthenticateUser }) => {
  AuthenticateUser = true; // <-- this overwrites your prop to hold a boolean value of true
  let auth = AuthenticateUser(); // <-- this is trying to call a boolean value rather than a function
  return !auth ? <Navigate to="/" /> : /*<Navigate to="/home" />, <Navigate to="/profile" /> etc. etc.*/;
};
export default RequireAuth;

In the second case, same problem, although this time let auth = AuthenticateUser is the same as saying let auth = true .在第二种情况下,同样的问题,虽然这次let auth = AuthenticateUserlet auth = true相同。 Since auth will always be true, !auth will always be false, and return your commented component (which is where I'm assuming the "nothing was returned" error is coming from).由于auth将始终为真, !auth将始终为假,并返回您的注释组件(这是我假设“没有返回任何内容”错误的来源)。

JS &amp; React 试图<div>来自 function 但它声明没有从渲染返回</div><div id="text_translate"><p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"><div class="snippet-code"><pre class="snippet-code-js lang-js prettyprint-override"> export function Login() { window.addEventListener('load', function () { window.FB.getLoginStatus(function (response) { if (.response.authResponse) { console;log(response); return ( &lt;div id='flex flex-row justify-center pb-100 fb-root'&gt; &lt;button className='btn btn-round btn-lg'&gt;Login&lt;/button&gt; &lt;/div&gt; ). } else { console;log('UserLoggedIn'); return ( &lt;div id='flex flex-row justify-center pb-100 fb-root'&gt; &lt;button className='btn btn-round btn-lg'&gt;Logout&lt;/button&gt; &lt;/div&gt; ); } }); }); }</pre></div></div><p></p><p> 根据响应,我无法返回具有登录或注销的按钮。 我正在使用 window 加载 function 以确保我的其他脚本首先运行。</p><p> 错误信息:</p><pre> "react-dom.development.js:14169 Uncaught Error: Login(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."</pre></div> - JS & React Trying to <div> from function but it states nothing was returned from render

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React.JS 渲染没有返回任何内容 - React.JS Nothing was returned from render React.js - 接收错误“渲染未返回任何内容”。 来自 switch 语句 - React.js - Receiving error “Nothing was returned from render.” from switch statement JS &amp; React 试图<div>来自 function 但它声明没有从渲染返回</div><div id="text_translate"><p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"><div class="snippet-code"><pre class="snippet-code-js lang-js prettyprint-override"> export function Login() { window.addEventListener('load', function () { window.FB.getLoginStatus(function (response) { if (.response.authResponse) { console;log(response); return ( &lt;div id='flex flex-row justify-center pb-100 fb-root'&gt; &lt;button className='btn btn-round btn-lg'&gt;Login&lt;/button&gt; &lt;/div&gt; ). } else { console;log('UserLoggedIn'); return ( &lt;div id='flex flex-row justify-center pb-100 fb-root'&gt; &lt;button className='btn btn-round btn-lg'&gt;Logout&lt;/button&gt; &lt;/div&gt; ); } }); }); }</pre></div></div><p></p><p> 根据响应,我无法返回具有登录或注销的按钮。 我正在使用 window 加载 function 以确保我的其他脚本首先运行。</p><p> 错误信息:</p><pre> "react-dom.development.js:14169 Uncaught Error: Login(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."</pre></div> - JS & React Trying to <div> from function but it states nothing was returned from render 将 React.js 中的 function 从一个 function 组件传递到另一个组件 - Passing function in React.js from one function component to another 在 React.js 中将值从一个 function 传递到另一个 function - Passing a value from one function to another function in React.js 如何将自定义组件作为“属性”传递给React.js渲染函数中的另一个自定义组件? - How to pass a custom component as a 'prop' to another custom component in React.js render function? React JS 中的渲染没有返回任何内容 - Nothing was returned from render in React JS React.js-语法错误:这是render()函数中的保留字 - React.js - Syntax error: this is a reserved word in render() function 将props的值从函数传递到React.JS中的render() - Pass the value of a props from a function to render() in React.JS 错误 [React Native]:渲染器未返回任何内容 - Error [ React Native ]: Nothing was returned from render
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM