javascript - 如何在react js中成功登录后重定向

标签 javascript reactjs react-router-dom

我正在使用构建一个 react 应用程序在这里我无法弄清楚如何在成功登录后重定向到 /dashboard 。任何帮助都会有用

在此文件中,我将用户名和密码传递给我的 redux 操作 this.props.login

signin.js

    handleLoginClick = () => {
        const { inputUserID, inputPassword } = this.state;

        this.login(inputUserID, inputPassword)

      };
    login = (username, password) => {
        this.props.login(username, password);

      };



  render() {
    const {
      showError,
      open,
      inputUserID,
      inputPassword,
      checkRememberID,
      showPhoneNumberDialog,
      showVerifyNumberDialog
    } = this.state;


    return (
      <div className="sign-in-dialog-container">

        <Dialog
          id="dialog-sign-in"
          className="dialog"
          open={open}
          onClose={this.handleClose}
          aria-labelledby="form-dialog-title"
          style={{

            backgroundColor: '#fff'
          }}
        >
          <DialogTitle id="form-dialog-title">Sign In</DialogTitle>
          <DialogContent className="dialog-content">
            <div className="dialog-content-form">
              <div className="form-field">
                <div className="content-label">ID</div>
                <FormControl fullWidth variant="outlined">
                  <OutlinedInput
                    fullWidth
                    type="text"
                    placeholder="User Name"
                    value={inputUserID}
                    onChange={this.handleTextChange("inputUserID")}
                    labelWidth={0}
                  />
                </FormControl>
              </div>

              <div className="form-field margin-top-16">
                <div className="content-label">Password</div>
                <FormControl fullWidth variant="outlined">
                  <OutlinedInput
                    fullWidth
                    type="password"
                    placeholder="**********"
                    value={inputPassword}
                    onChange={this.handleTextChange("inputPassword")}
                    labelWidth={0}
                  />
                  {showError ? (
                    <FormHelperText className="password-incorrect-text">
                      Password is incorrect
                    </FormHelperText>
                  ) : null}
                </FormControl>
              </div>

              <div className="form-field">
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={checkRememberID}
                      onChange={this.handleCheckboxChange("checkRememberID")}
                      value="checkRememberID"
                      color="primary"
                    />
                  }
                  label="Remember ID"
                />
              </div>

              <div className="form-field">
                <Button
                  className="next-button custom-button-style"
                  fullWidth
                  onClick={this.handleLoginClick}
                  variant="contained"
                  color="primary"
                >
                  Next
                  </Button>
              </div>


            </div>
          </DialogContent>

          <div className="bottom-row">
            <span className="helper-text">
              Don't have an account?
                <span
                onClick={this.handleSignUpClick}
                className="strong cursor-pointer"
              >
                {" "}
                  Sign Up
                </span>
            </span>
          </div>
        </Dialog>
      </div>
    );
  }

}

const mapStateToProps = state => ({
  user: state.userReducer,
  productPageReducer: state.productPageReducer,
  isAuthenticated: state.auth.access_token,
});

const mapDispatchToProps = {
  getProductList,
  login,
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SignIn);

authAction.js

export const login = (username, password) => (dispatch) => {
    //User Loading:
    dispatch({ type: USER_LOADING });
    //Make API Call here
    var myHeaders = new Headers();
    myHeaders.append("Authorization", "Basic dG9wc2VsbGVyOnRvcHNlbGxlcg==");

    var formdata = new FormData();
    formdata.append("username", username);
    formdata.append("password", password);
    formdata.append("grant_type", "password");

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: formdata,
        redirect: 'follow'
    };

    fetch("https://api.XXXXXXXXXXXXX.com/oauth/token", requestOptions)
        .then(response => response.json())
        .then(
            res => {
                if (res.access_token && res.refresh_token) {
                    window.localStorage.access_token = res.access_token;
                    window.localStorage.refresh_token = res.refresh_token;
                    dispatch({
                        type: LOGIN_SUCCESS,
                        user: res
                    });
                } else {
                    dispatch({
                        type: LOGIN_FAIL,
                        message: 'Unauthorised User'
                    })
                }

            }
        )
        .catch(error =>
            dispatch({
                type: LOGIN_FAIL,
                message: error
            })
        );

}

这里我想弄清楚如何在成功登录后重定向到/dashboard。我也在使用react-router-dom。

最佳答案

你可以这样做,但不要:

CASE LOGIN_SUCCESS:
   window.location.href = '/dashboard';
   break;

这只是一个黑客行为。使用 window.location.href 重定向会使您的应用失去 SPA 优势。

由于您使用的是React-redux,因此您必须在reducer中保存用户登录状态。让 App.jsx 订阅登录状态,如果为 false,则渲染 Redirect 组件。

为什么您的应用在重定向后忘记登录状态:

因为您在 window.localStorage 上做错了什么:

window.localStorage.whatever_token = 'foobarbaz';

这行不通。 localStorage 不应该这样使用。

相反,您应该:

window.localStorage.setItem('my_token', 'awesome_jwt_token');

稍后:

const isLoggedIn = () = > {
  const token =  window.localStorage.getItem('my_token');
  if (token) {
    //    can ommit this flow
    //    const isLoggedIn = askServerIfThisTokenIsValid(token);
    //    if (isLoggedIn) {
    //        return true;
    //    } else {
    //        window.localStorage.removeItem('my_token');
    //    }
    return true; // but not safe - handle 403 error in all api calls
  } else {
    return false;
  }
  
};

关于javascript - 如何在react js中成功登录后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60812763/

相关文章:

javascript - 修改javascript中的if else条件

reactjs - React-Native是单线程执行还是多线程执行?

javascript - 如何使用javascript通过api在我的谷歌应用程序脚本中运行一个函数

javascript - 根据宽度调整图像大小

javascript - 如何使用 React 测试库测试点击事件的 stopPropagation?

javascript - 如何使用本地网络中的 Node 后端访问我的 React 应用程序?

reactjs - Uncaught Error : useNavigate() may be used only in the context of a <Router> component

javascript - 单击特定卡时在另一页上呈现卡详细信息

reactjs - react-router-dom-链接和history.push之间的区别?

javascript - 获取 MySql 数据到 PHP 数组并转换为 Javascript 数组