javascript - 如何使用 React Router 返回重定向?
问题描述
我有点 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?`} <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);```
解决方案
我建议使用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('/')
您可以详细了解其中的每一个,并根据您未来的用例决定哪一个,但现在这些选项中的任何一个都可以在这里解决您的问题。
关于你的侧面问题。您所做的确实是脏编码,您应该通过函数参数传递变量。没有像您现在所做的那样将这些值全局存储在您的文件中。
推荐阅读
- xpath - 谷歌表格上 Importxml 的 XPATH
- spring-boot - Spring security:jwt中的Http安全方法
- javascript - 如何将历史道具与其他道具一起使用
- excel - 将 Excel 数组公式转换为 VBA 代码
- titanium - 使用钛5.2.2如何使用钛检测器?
- hash - 逆向工程结合 CRC/命令字节
- python-3.x - 蟒蛇 | 熊猫 | 使用 Lambda 多个条件计算具有值和 NAN 的行
- javascript - 从另一个 axios 承诺进行 axios 调用并保存返回的数据
- haskell - 在 Mac 上安装 Haskell 时构建失败,出现 NonZeroExit 77,ghcup --cache install" failed
- kotlin - 商店关闭后不会删除 xd.lck 锁定文件