【问题标题】:handling events in react在反应中处理事件
【发布时间】:2021-08-19 19:35:36
【问题描述】:

我需要创建一个登录页面,当我单击提交按钮时,它应该导航到仪表板页面。以下是我的代码,其中有什么问题。当我在登录页面中提供详细信息并单击登录时,详细信息消失并且未导航到仪表板。

import React, { Component, useState  } from "react";
import axios from 'axios';
import { setUserSession } from '../utils/common';
function Login(props) {
    const username = useFormInput('');
  const password = useFormInput('');
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
 
  // handle button click of login form
  const handleLogin = () => {
    props.history.push('/dashboard');
  }
      

        return (
            <form>
                <h3>Sign In</h3>

                <div className="form-group">
                    <label>Email address</label>
                    <input type="email" className="form-control" placeholder="Enter email" />
                </div>

                <div className="form-group">
                    <label>Password</label>
                    <input type="password" className="form-control" placeholder="Enter password" />
                </div>

                <div className="form-group">
                    <div className="custom-control custom-checkbox">
                        <input type="checkbox" className="custom-control-input" id="customCheck1" />
                        <label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
                    </div>
                </div>

                
                {error && <><small style={{ color: 'red' }}>{error}</small><br /></>}<br />
                <input  type="button" className="btn btn-primary btn-block" value={loading ? 'Loading...' : 'Sign-in'} onClick={handleLogin} disabled={loading} /><br />
                <p className="forgot-password text-right">
                    Forgot <a href="#">password?</a>
                </p>
            </form>
        );
        }

        const useFormInput = initialValue => {
            const [value, setValue] = useState(initialValue);
           
            const handleChange = e => {
              setValue(e.target.value);
            }
            return {
              value,
              onChange: handleChange
            }
          }
          
           
          export default Login;

【问题讨论】:

    标签: javascript reactjs authentication react-router


    【解决方案1】:

    您是否为/dashboard 定义了路线。在没有反应路由器设置的情况下,一切都在代码沙箱中工作。伪代码如下所示

    <Switch>
      <Route path="/dashboard">
        <DashboardComponent />
      </Route>
    </Switch>
    

    【讨论】:

    • 我需要在哪里添加这个代码sn-p?在“handleLogin”中?
    • 将片段添加到我的 login.js 文件后,现在导航没有发生。但是当我给出提交按钮时,登录的详细信息仍然存在!
    猜你喜欢
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多