【问题标题】:Conditional rendering isn't behaving as expected条件渲染未按预期运行
【发布时间】:2022-06-13 17:17:42
【问题描述】:

我正在从底部的代码生成登录状态。然后,我将生成的状态(真或假)提升到父组件(App.js 文件),然后进一步尝试实现条件渲染,但它的行为不符合预期。有什么建议吗?

我已附上以下文件。我的网站仍然显示登录页面,并且从不呈现其他条件内容。

App.js 文件

import "./App.css";
import LoginPage from "./Login/LoginPage";
import NewPost from "./Posts/NewPost";
import Posts from "./Posts/Posts";
import PostList from "./Posts/PostList";
import { useState } from "react";

const expenses = [
  {
    name: "Lakshay Gupta",
    content:
      " Amet minim mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit. Exercitation veniam consequat sunt nostrud amet.",
    posted: "5mins ago",
    comments: "16 comments",
  },
  {
    name: "Naman Sukhija",
    content:
      " Amet minim mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit. Exercitation veniam consequat sunt nostrud amet.",
    posted: "1hour ago",
    comments: "24 comments",
  },
  {
    name: "William Harris",
    content:
      " Amet minim mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit. Exercitation veniam consequat sunt nostrud amet.",
    posted: "3mins ago",
    comments: "29 comments",
  },
];

function App() {
  let loggedIn = false;

  const submitLoginHandler = (ifLoggedIn) => {
    loggedIn= ifLoggedIn;
    console.log(loggedIn);

  };

  return (
    <div className="App">
      {!loggedIn ? (
        <LoginPage onSubmitLogin={submitLoginHandler}></LoginPage>
      ) : (
        <div>
          <NewPost></NewPost>
          <PostList items={expenses}></PostList>{" "}
        </div>
      )}
    </div>
  );
}

export default App;

LoginPage.js 文件

import React from "react";
import "./LoginPage.css";
import { useState } from "react";

export default function LoginPage(props) {

  const [loggedIn, setLoggedIn] = useState(false);

  const loginHandler = (e) => {
    e.preventDefault();
     setLoggedIn(true);
     props.onSubmitLogin(loggedIn);
  }
  return (
    <div>
      <form className="form-dimensions">
          <div className="mb-4 custom-heading">
              WELCOME BACK
          </div>
          <div className="mb-4 custom-subheading">
              Login into your account
          </div>
        <div className="mb-3">
          <label htmlFor="exampleInputEmail1" className="form-label email-custom form-color">
            Email or Username
          </label>
          <input
            type="email"
            className="form-control"
            id="exampleInputEmail1"
            aria-describedby="emailHelp"
            placeholder="Enter your email or username"
          />
          
        </div>
        <div className="mb-3">
            <div className="label-inline">
          <label htmlFor="exampleInputPassword1" className="form-label form-color password-custom label-inline">
            Password                                     
          </label>
          <label htmlFor="exampleInputPassword2" className="forgot-password-custom form-label form-color label-inline">
              Forgot password?
          </label>
            </div>
          
          
          <input
            type="password"
            className="form-control"
            id="exampleInputPassword1"
            placeholder="Enter your password"
          />
        </div>
        
        <button type="submit" className="btn btn-primary" onClick={loginHandler} >
          Login now
        </button>
        <div className="custom-ending">
            Not registered yet? <span>Register →</span>
        </div>
      </form>
    </div>
  );
}

【问题讨论】:

  • 您还没有解除状态,您只是在父级中声明了一个变量,每次渲染都会重新声明。将useState声明移动到父组件,并将setLoggedIn方法传递给登录组件。
  • 你在任何意义上都没有提升状态。 1. 你的 App 有 let loggedIn = false; 而不是状态 2. 你的 Login 组件有自己的状态
  • @pilchard 我试图在单击按钮时从登录组件生成“真”或“假”状态。然后我试图将该状态传递给父组件。

标签: javascript reactjs frontend


【解决方案1】:

你需要在App中使用State而不是LoginPage.js。

这是因为状态如果更新就会被获取。如果值按照你定义的方式改变,React 不会重新渲染。

所以你应该在点击登录按钮时发送登录状态(true),然后在 App 中获取它并将其解析为 App.js 的状态。

LoginPage.jsx

import React from "react";
import { useState } from "react";

export default function LoginPage(props) {
  const loginHandler = () => {
    props.onSubmitLogin(true);
  };
  return (
    <div>
      <form className="form-dimensions">
        <div className="mb-4 custom-heading">WELCOME BACK</div>
        <div className="mb-4 custom-subheading">Login into your account</div>
        <div className="mb-3">
          <label
            htmlFor="exampleInputEmail1"
            className="form-label email-custom form-color"
          >
            Email or Username
          </label>
          <input
            type="email"
            className="form-control"
            id="exampleInputEmail1"
            aria-describedby="emailHelp"
            placeholder="Enter your email or username"
          />
        </div>
        <div className="mb-3">
          <div className="label-inline">
            <label
              htmlFor="exampleInputPassword1"
              className="form-label form-color password-custom label-inline"
            >
              Password
            </label>
            <label
              htmlFor="exampleInputPassword2"
              className="forgot-password-custom form-label form-color label-inline"
            >
              Forgot password?
            </label>
          </div>

          <input
            type="password"
            className="form-control"
            id="exampleInputPassword1"
            placeholder="Enter your password"
          />
        </div>

        <button
          type="submit"
          className="btn btn-primary"
          onClick={loginHandler}
        >
          Login now
        </button>
        <div className="custom-ending">
          Not registered yet? <span>Register →</span>
        </div>
      </form>
    </div>
  );
}

还有 app.js

import LoginPage from "./LoginPage";
import { useState } from "react";

const expenses = [
  {
    name: "Lakshay Gupta",
    content:
      " Amet minim mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit. Exercitation veniam consequat sunt nostrud amet.",
    posted: "5mins ago",
    comments: "16 comments"
  },
  {
    name: "Naman Sukhija",
    content:
      " Amet minim mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit. Exercitation veniam consequat sunt nostrud amet.",
    posted: "1hour ago",
    comments: "24 comments"
  },
  {
    name: "William Harris",
    content:
      " Amet minim mollit non deserunt ullamco est sit aliqua dolor do amet sint. Velit officia consequat duis enim velit mollit. Exercitation veniam consequat sunt nostrud amet.",
    posted: "3mins ago",
    comments: "29 comments"
  }
];

function App() {
  const [loggedIn, setLoggedIn] = useState(false);
  const submitLoginHandler = (e) => {
    setLoggedIn(e);
    console.log(e);
  };

  return (
    <div className="App">
      {!loggedIn ? (
        <LoginPage onSubmitLogin={submitLoginHandler} />
      ) : (
        <div>Post to show</div>
      )}
    </div>
  );
}

export default App;

您可以在这里查看完整答案:https://codesandbox.io/s/clever-hermann-83048s

希望对你有帮助!

【讨论】:

  • @LakshayGupta 很高兴我能帮上忙,如果对你有帮助请投票^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 2015-05-15
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多