首页 > 解决方案 > 使用 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 不是强制性的。此外,我不想让我的应用程序更复杂,并且有另一个依赖项来实现重定向等基本功能。

所以现在我必须让它更加复杂和隐含。也许我错过了什么?

欢迎任何帮助。

标签: reactjsreduxredux-sagareact-router-dom

解决方案


通过 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);

推荐阅读