You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何根据布尔值状态切换组件显示内容?

解决方案:在React组件内根据登录状态切换内容显示

你的核心问题是普通变量无法触发React组件重新渲染,所以successfulAuth变化后页面不会更新。需要用React的useState来管理状态,同时要正确处理异步API调用后的状态更新。以下是具体修改方案:

关键修改点

  • 将successfulAuth改为React状态变量,新增authResult存储API响应结果(供跳转页使用)
  • 异步API调用中正确更新状态,确保状态变化触发组件重渲染
  • 使用条件渲染控制登录表单和跳转页的显示

修改后的完整代码

function Login() {
  const nav = useNavigate();
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [appid, setAppid] = React.useState("");
  // 用useState管理登录状态和API响应结果
  const [successfulAuth, setSuccessfulAuth] = React.useState(false);
  const [authResult, setAuthResult] = React.useState(null);

  const api = new bimplusAPI();

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // 验证输入完整性
    const isInputValid = email !== "" && password !== "" && appid !== "";
    if (!isInputValid) return;

    try {
      const result = await api.authorise(email, password, appid);
      if (result.status === 200) {
        console.log("Auth Successful");
        setSuccessfulAuth(true);
        setAuthResult(result); // 保存API响应供跳转页使用
      } else {
        console.log("Auth Failed");
        // 可在此添加错误提示逻辑
      }
    } catch (error) {
      console.error("API调用出错:", error);
      // 处理网络错误等异常情况
    }
  };

  return (
    <div className="app">
      {/* 登录表单:仅在未授权时显示 */}
      {!successfulAuth && (
        <form onSubmit={handleSubmit}>
          <label htmlFor="email">Email: </label>
          <input
            type="text"
            id="email"
            name="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
          <br />
          <label htmlFor="pass">Password: </label>
          <input
            type="password" // 密码输入建议用password类型
            id="pass"
            name="pass"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          <br />
          <label htmlFor="appid">App ID: </label>
          <input
            type="text"
            id="appid"
            name="appid"
            value={appid}
            onChange={(e) => setAppid(e.target.value)}
          />
          <br />
          <input type="submit" value="Submit" />
        </form>
      )}

      {/* 跳转页(项目选择页):仅在授权成功时显示 */}
      {successfulAuth && authResult && (
        <div>
          <h1>Project select page</h1>
          <p>Example HTML that should be displayed only if 'successfulAuth' === true</p>
          {/* 这里可以直接使用authResult中的数据,比如: */}
          {/* <p>用户授权令牌: {authResult.data.token}</p> */}
        </div>
      )}
    </div>
  );
}

export default Login;

额外优化说明

  • 用async/await替代then,让异步代码逻辑更清晰
  • 密码输入框改为type="password",符合安全规范
  • 表单输入绑定value属性,转为受控组件,符合React最佳实践
  • 添加异常捕获,处理API调用失败的情况

内容的提问来源于stack exchange,提问作者csPYTHONcs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:01:17