到目前为止,我一直在从React组件重定向到用户面板,但我想应用不同的方法,我想在从传奇故事本身获得成功响应后重定向。
为此,我尝试使用redux-first-history
(它得到了react-router6的支持(。我遵循了他们的文档,几乎所有东西都在工作,但一个动作@@router/CALL_HISTORY_METHOD
被调用了两次。
这是我的路线
export default function App() {
return (
<AuthProvider>
<Router history={history}>
<Routes>
<Route element={<Layout />}>
<Route path="/" element={<PublicPage />} />
<Route path="/login" element={<LoginPage />} />
<Route
path="/protected"
element={
<RequireAuth>
<ProtectedPage />
</RequireAuth>
}
/>
</Route>
</Routes>
</Router>
</AuthProvider>
);
}
它贯穿整个项目,下面是我的商店。
import { applyMiddleware, compose, createStore } from "redux";
import { persistReducer, persistStore } from "redux-persist";
import storage from "redux-persist/lib/storage";
import createSagaMiddleware from "redux-saga";
import rootReducer from "../store/reducers";
import { watchAuth } from "../store/sagas/index";
import { createReduxHistoryContext } from "redux-first-history";
import { createBrowserHistory } from "history";
const composeEnhancers =
process.env.NODE_ENV === "development"
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
: null || compose;
const { createReduxHistory, routerMiddleware } = createReduxHistoryContext({
history: createBrowserHistory(),
oldLocationChangePayload: true,
showHistoryAction: true,
});
const sagaMiddleware = createSagaMiddleware();
const middleware = [sagaMiddleware, routerMiddleware];
const persistConfig = {
key: "root",
storage,
whitelist: ["auth"],
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = createStore(
persistedReducer,
composeEnhancers(applyMiddleware(...middleware)),
);
const persistor = persistStore(store);
sagaMiddleware.run(watchAuth);
export const history = createReduxHistory(store);
export default store;
export { persistor };
和我的佐贺
import { call, delay, put } from "redux-saga/effects";
import axios from "../../../config/axios";
import {
authFail,
authStart,
authSuccess,
checkAuthTimeout,
logout,
logoutSucceed,
setAlert,
} from "../../actions/auth/auth";
import { LOGIN_API } from "../../apiCollecitions";
import { push } from "redux-first-history";
export function* authLoginSaga(action) {
yield put(authStart());
const authData = {
email: action.email,
password: action.password,
};
try {
const response = yield axios.post(
`${LOGIN_API}?lng=${localStorage.getItem("i18nextLng")}&active=true`,
authData,
);
const expirationTokenTime = 3600;
const expirationDate = yield new Date(new Date().getTime() + expirationTokenTime * 1000);
yield localStorage.setItem("token", response.data.token);
yield localStorage.setItem("expirationDate", expirationDate);
yield put(authSuccess(response.data.token));
yield put(push("/protected")); //should redirect to the specified route
} catch (error) {
yield put(authFail(error.response.data.message));
}
}
我还为其设置了一个示例GitHub回购,供您参考。
如果你不想让事情复杂化,你可以简单地执行window.location="/login"
,或者你可以从react router添加一个使用重定向并从返回函数返回这行
if(this.state.authSuccess)<Redirect to="/login" />