reactjs - 使用 redux-saga 重定向反应路由器
问题描述
我有 redux-saga,它应该在成功登录后将用户重定向到主页。我不使用react-router-redux
或那样做,所以我的路由器没有连接到状态。
这是我的登录组件
const AdminLogin: React.FC<RouteComponentProps> = ({history}) => {
const [form, setForm] = useState({username: '', password: ''});
const user = useSelector(getAdminUser);
const dispatch = useDispatch();
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
dispatch(makeLoginAsync(form));
};
useEffect(() => {
if (user && user.token) {
history.push('/admin/main'); // here it is
}
}, [user, history]);
return (
<form onSubmit={handleSubmit} className="admin-login">
// FORM HTML CODE
</form>
);
};
export default withRouter(AdminLogin);
请注意,我正在向 Action 发送表单,然后 Saga 正在监听我的 Action 并执行所有逻辑和效果。我认为在 Saga 代码中进行重定向会更好。但我不能?
成功登录后,Reducer更改状态设置用户身份验证令牌。如果我有令牌,我会将其视为用户登录并将他重定向到另一个页面。
如您所见,我直接在组件中实现了这个逻辑(使用 Selector)。但是我觉得非常难看。
实际上,我history
只能在组件中访问对象(如果组件用 包裹withRouter
)。
如果我使用react-router-redux
,我可以做类似的事情
import { push } from 'react-router-redux'
并使用push
函数从 Saga 重定向。我是 React 的新手,我听说将路由器连接到 redux 不是强制性的。此外,我不想让我的应用程序更复杂,并且有另一个依赖项来实现重定向等基本功能。
所以现在我必须让它更加复杂和隐含。也许我错过了什么?
欢迎任何帮助。
解决方案
通过 dispatch 事件传递历史,然后使用它在 redux 中推送路由
const AdminLogin: React.FC<RouteComponentProps> = ({history}) => {
const [form, setForm] = useState({username: '', password: ''});
const user = useSelector(getAdminUser);
const dispatch = useDispatch();
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
dispatch(makeLoginAsync({form,history}));
};
useEffect(() => {
if (user && user.token) {
history.push('/admin/main'); // here it is
}
}, [user, history]);
return (
<form onSubmit={handleSubmit} className="admin-login">
// FORM HTML CODE
</form>
);
};
export default withRouter(AdminLogin);
推荐阅读
- android - 如何使我自己的注释处理器增量?
- visual-studio - 如何更好地诊断链接器错误 LNK2022?
- android - TextInputEditText,如何将提示对齐到上边距
- unity3d - 启用动画器时,运行时缺少游戏对象精灵
- bash - 手动将字符串列表传递给管道
- javascript - 尝试播放 youtube 视频 javascript 时“.playVideo 不是函数”
- node.js - TypeScript 在 Express 中添加自定义请求标头
- c# - 当用户在 DataGridView 中编辑单元格时,BindingSource 不更新(简单的损坏示例)
- r - 如何动态生成数据框变量名称并使用它来处理现有数据框变量?
- ios - iTunes 如何检测 DFU 模式,我可以更改它以在 macOS 上打开另一个程序吗