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)
}
};
我无法以单页方式重定向到我的仪表板,我搜索了很多但没有得到任何有用的信息。我正在使用 React Router v4。您能否建议我是否以正确的方式使用 JWT 进行此用户登录。
最佳答案
使用此 history library 在 history.js
文件中创建您自己的 history
.
//history.js
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
export default history
将其提供给您的路由器:
<Router history = {history}>.....</Router>
然后您可以使用此 history
对象从任何地方重定向。在你的行动中:
import history from './history'
history.push(`${app}/dashboard`)
关于javascript - react-redux 登录后重定向到其他页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46954647/