简体   繁体   English

then() 成功后 React 组件不渲染

[英]React component not rendering after then() succeeds

I want to render some JSX based on a condition, but it is not happenning.我想根据条件渲染一些 JSX,但它没有发生。 Below is my code -下面是我的代码 -

chkAccess().then((result) => {
    console.log(result)
    if(result) {
        alert("Access Granted")
        return (
            <div className='login_container p-5 m-5 bg-dark'>
            <h1 className='text-center p-3'>You are seeing this page because you are a Manager</h1>
            </div>
        )
    }
    alert("Access Denied")
    return(<Access_denied />)

The JSX returned is not getting rendered.返回的 JSX 没有被渲染。 Why is it so and how I can i fix it?为什么会这样,我该如何解决?

I expect the returned code to be rendered, but It did not happen.我希望返回的代码被渲染,但它没有发生。

From what I can see your implementation is wrong.据我所知,您的实施是错误的。 If you need to first check the user's access you should display loading and after checking the permission set the state based on the permission the user has and then render the JSX based on that state. If you don't want the user to see a loading spinner, You can use the Server side and before rendering the component you check如果您需要首先检查用户的访问权限,您应该显示加载并在检查权限后根据用户拥有的权限设置 state,然后根据该 state 呈现 JSX。如果您不希望用户看到加载微调器,您可以使用服务器端并在呈现您检查的组件之前

const [hasAccess, setHasAccess] = useState(null);

  useEffect(() => {
    chkAccess().then((result) => {
      setHasAccess(!!result);
    });
  }, []);

  if (hasAccess === null) return <Loading />;

  if (!hasAccess) {
    alert("Access Denied");
    return <Access_denied />;
  }

  if (hasAccess)
    return (
      <div className="login_container p-5 m-5 bg-dark">
        <h1 className="text-center p-3">
          You are seeing this page because you are a Manager
        </h1>
      </div>
    );

You should use a state to keep track of your async call result, then render different elements based on the current state.你应该使用 state 来跟踪你的异步调用结果,然后根据当前的 state 渲染不同的元素。

Here is an example based on the implementation:下面是一个基于实现的例子:

import { useEffect, useState } from "react";

export default function App() {
  const [hasAccess, setHasAccess] = useState(false);
  const [loading, setLoading] = useState(false);

  // Here we mock access check.
  const chkAccess = async () => Promise.resolve(() => true);

  useEffect(() => {
    setLoading(true);
    const timer = setTimeout(() => {
      setHasAccess(chkAccess());
      setLoading(false);
    }, 1000);
    return () => clearTimeout(timer);
  }, []);

  const renderContent = () => {
    if (loading) {
      return "Loading...";
    }
    if (!hasAccess) {
      return "Access Denied";
    }
    return "Authenticated";
  };

  return <div className="App">{renderContent()}</div>;
}

编辑 74427705

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM