在登录后,react-redux重定向到其他页面

tap*_*ave 9 javascript reactjs react-router redux react-redux

action.js:

export const login = creds => {
    console.log(`${url}/login`);
    const requestOptions = {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
        },
        body: creds
    };

    return function(dispatch) {
        dispatch({ type: LOGIN_REQUEST });
        function timer() {
            return fetch(`${url}/login`, requestOptions).then(response => {
                if (!response.ok) {
                    console.log(response);
                    return response.json().then(json => {
                        var error = new Error(json.message);
                        error.response = response;
                        throw error;
                    });
                } else {
                    console.log("3");
                    return response.json();
                }
            }).then(user => {
                if (user.message === "ok") {
                    localStorage.setItem("token", user.token);
                    dispatch({ type: LOGIN_SUCCESS, payload: user.token });
                    window.location.href = `${app}/dashboard`;
                } else {
                    const error = user.message;
                    throw new Error(error);
                }
            }).catch(function(error) {
                dispatch(loginError(error));
            });
        }
        setTimeout(timer, 5000)
    }
};
Run Code Online (Sandbox Code Playgroud)

我无法以单页方式重定向到我的仪表板,我搜索了很多,但我没有得到任何有用的东西.我正在使用React Router v4.能否请您建议我是否以正确的方式使用JWT进行此用户登录.

Anu*_*thi 7

使用此历史记录库historyhistory.js文件中创建自己的文件.

//history.js
import createHistory from 'history/createBrowserHistory'

const history = createHistory()

export default history
Run Code Online (Sandbox Code Playgroud)

将它提供给您的路由器:

<Router history = {history}>.....</Router>
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用此history对象从任何位置重定向.在你的行动中:

import history from './history'
history.push(`${app}/dashboard`)
Run Code Online (Sandbox Code Playgroud)