首页 > 解决方案 > 如何使用 React Router 返回重定向?

问题描述

我有点 React 菜鸟。

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

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

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

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);```


标签: javascriptreactjsredirectreact-router

解决方案


我建议使用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()

最后,替换<Redirect to={{ pathname: '/' }} />为:

return history.push('/')

或者

return history.replace('/')

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


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


推荐阅读