所以基本上我正在做一个登录请求,成功后我想发送响应并将用户重定向到个人资料页面。
因此,调度响应工作正常,但在进行dispatch(push('/profile'));
URL 更改时,但配置文件组件不会被呈现。
如果我只是在没有 axios 请求的情况下执行以下代码,它可以正常工作并重定向。
export function logIn(values) {
return (dispatch) => {
dispatch({ type: LOGIN_USER, payload: {email: values.email} });
dispatch(push('/profile'));
};
}
我想要做的实际代码。在发送了可以正常工作的响应之后,我的 redux 商店得到了更新,但重定向不起作用。它将 url 更改为 /profile 但视图没有改变
import axios from 'axios';
import { push } from 'connected-react-router';
const ROOT_URL = `${process.env.REACT_APP_SERVER_PATH}`;
export const LOGIN_USER = 'LOGIN_USER';
export function logIn(values) {
const url = `${ROOT_URL}/login`;
const request = axios({
method: 'POST',
url: url,
data: values,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
return (dispatch) => {
request.then((response) => {
dispatch({ type: LOGIN_USER, payload: response.data.user });
dispatch(push('/profile'));
})
request.catch((error) => {
// do something
})
};
}
配置存储:
import { createBrowserHistory } from 'history';
import { createLogger } from 'redux-logger';
import { applyMiddleware, compose, createStore } from 'redux'
import { routerMiddleware } from 'connected-react-router'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/es/storage'
import thunk from 'redux-thunk'
import createRootReducer from './reducers'
export const history = createBrowserHistory();
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const persistConfig = {
key: 'root',
storage: storage,
whitelist: ['auth'] // can eention specific data root name
};
const reducers = persistReducer( persistConfig, createRootReducer(history));
export default () => {
const store = createStore(
reducers,
composeEnhancers(applyMiddleware(routerMiddleware(history), thunk, createLogger()))
);
let persistor = persistStore(store)
return { store, persistor }
}