【问题标题】:How can you return Redirect using React Router?如何使用 React Router 返回重定向?
【发布时间】:2020-07-20 19:09:19
【问题描述】:

我有点 React 菜鸟。

我正在尝试创建条件重定向,因此编写了一个函数 (errorCapture),其中一个结果应触发重定向。我将语句返回到返回语句中的子组件 (ErrorOrReroute),在我的功能组件中,希望这会导致页面更改。没有这样的运气!

  • 我知道该路线在其他情况下有效。
  • 有一个console.log('redirect');在函数中返回的语句旁边,该语句按预期显示,因此我知道该函数按预期工作。
  • 控制台中没有其他错误消息。

任何帮助将不胜感激。谢谢!!

(附带问题:完全在另一个组件的代码中编写一个组件是否“可以”?行得通吗?它是否被认为是脏编码,如果我可以确定它不需要在其他地方使用过?谢谢。)

import PropTypes from 'prop-types';
import AuthContainer from './auth-container';
import { Button, Form, Message, Segment } from 'semantic-ui-react';
import { NavLink, useParams, Redirect } from 'react-router-dom';
import { withFormik } from 'formik';
import { PasswordResetConfirmService } from '../../utils/api/auth/auth.js';
import { mapFormError, NonFieldErrors } from '../../modules/forms';
import { t } from 'ttag';


let uidString = '';
let tokenString = '';
let executed = false;


const PasswordResetConfirmPage = ({ logged, values, handleChange, handleBlur, handleSubmit, isSubmitting, errors }) => {
  const { token, uid } = useParams();
  uidString = uid;
  tokenString = token;

  const ErrorOrReroute = () => {
    const errorCapture = () => {
      if (Object.keys(errors).length === 0) return false;
      if (Object.keys(errors).includes('uid') || Object.keys(errors).includes('token')) return true;
    };

    if (logged && !errorCapture()) {
      console.log('redirect');
      return <Redirect to={{ pathname: '/' }} />;
    } else if (executed && errorCapture()) {
      return (
        <Message negative>
          {'Password update failed :( Please request another password-reset email.'}
        </Message>
      );
    } else return null;
  };

  return (
    <AuthContainer title={t`Reset Password`}>

      <Form size="large" onSubmit={handleSubmit}>
        <Segment stacked>
          <Form.Input fluid icon="lock" iconPosition="left" placeholder={t`New Password`} type="password" name="new_password1" onChange={handleChange} onBlur={handleBlur} value={values.new_password1} error={mapFormError(errors, 'new_password1')} />
          <Form.Input fluid icon="lock" iconPosition="left" placeholder={t`Repeat New Password`} type="password" name="new_password2" onChange={handleChange} onBlur={handleBlur} value={values.new_password2} error={mapFormError(errors, 'new_password2')} />
          <NonFieldErrors errors={errors} />
          <Button primary fluid size="large" type="submit" loading={isSubmitting} disabled={isSubmitting} > {' '} {t`Confirm New Password`}{' '} </Button>
          <ErrorOrReroute />
        </Segment>
      </Form>

      <Message> {' '} {t`Know your password?`} &nbsp; <NavLink to="/login">{t`Login`}</NavLink>{' '} </Message>

    </AuthContainer>
  );
};

const withRegistrationErrors = withFormik({
  mapPropsToValues: () => ({ new_password1: '', new_password2: '', uid: '', token: '' }),
  handleSubmit: (values, { props, setSubmitting, setErrors }) => {
    values.uid = uidString;
    values.token = tokenString;
    executed = true;
    PasswordResetConfirmService(values)
      .then(() => {
        setSubmitting(false);
        props.toggleLoggedState();
      })
      .catch(errors => {
        setErrors(errors);
      });
  }
});

PasswordResetConfirmPage.propTypes = {
  values: PropTypes.object,
  handleChange: PropTypes.func,
  handleBlur: PropTypes.func,
  handleSubmit: PropTypes.func,
  isSubmitting: PropTypes.bool,
  errors: PropTypes.object,
  email: PropTypes.string,
  toggleLoggedState: PropTypes.func,
  logged: PropTypes.bool
};

export default withRegistrationErrors(PasswordResetConfirmPage);```


【问题讨论】:

    标签: javascript reactjs redirect react-router


    【解决方案1】:

    我建议使用history 在此处更改实现条件重定向:

    通过将useHistory 添加到您的react-router-dom 导入来做到这一点,如下所示:

    import { NavLink, useParams, useHistory } from 'react-router-dom';
    // You won't need Redirect anymore
    

    然后在const { token, uid } = useParams();下添加这一行:

    const history = useHistory()
    

    最后,将&lt;Redirect to={{ pathname: '/' }} /&gt; 替换为:

    return history.push('/')
    

    return history.replace('/')
    

    您可以详细了解其中的每一个,并根据您未来的用例决定哪一个,但现在这些选项中的任何一个都可以解决您的问题。


    关于你的附带问题。您所做的确实是脏编码,您应该通过函数参数传递变量。不像您现在所做的那样将这些值全局存储在您的文件中。

    【讨论】:

    • 谢谢巴里,非常感谢。我会试试看!
    • 不客气,我希望这是你需要的!快乐编码:)
    猜你喜欢
    • 2018-06-05
    • 2021-08-19
    • 2018-09-25
    • 2018-01-07
    • 2017-12-11
    • 2016-02-21
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    相关资源
    最近更新 更多