我正在使用react-redux和标准的react-routing。我需要在明确的行动后重定向。
例如:我已经注册了几个步骤。行动结束后:
function registerStep1Success(object) {
return {
type: REGISTER_STEP1_SUCCESS,
status: object.status
};
}
我希望他使用registrationStep2重定向到页面。怎么做?
P.S。在历史浏览器' / registrationStep2'从来没有。只有在成功注册结果页面后,才会显示此页面。
答案 0 :(得分:49)
使用React Router 2+,无论您在哪里发送操作,都可以致电browserHistory.push()
(或hashHistory.push()
,如果您使用的话):
import { browserHistory } from 'react-router'
// ...
this.props.dispatch(registerStep1Success())
browserHistory.push('/registrationStep2')
如果您使用的是异步动作创建者,也可以这样做。
答案 1 :(得分:21)
你签出了react-router-redux吗?该库可以将react-router与redux同步。
以下是有关如何使用react-router-redux的推送操作实现重定向的文档中的示例。
import { routerMiddleware, push } from 'react-router-redux'
// Apply the middleware to the store
const middleware = routerMiddleware(browserHistory)
const store = createStore(
reducers,
applyMiddleware(middleware)
)
// Dispatch from anywhere like normal.
store.dispatch(push('/foo'))
答案 2 :(得分:4)
在Eni Arinde上建立之前的答案(我没有评论的声誉),以下是在异步操作后如何使用store.dispatch
方法:
export function myAction(data) {
return (dispatch) => {
dispatch({
type: ACTION_TYPE,
data,
}).then((response) => {
dispatch(push('/my_url'));
});
};
}
诀窍是在动作文件中而不是在reducers中执行,因为reducer不应该有副作用。
答案 3 :(得分:2)
我们可以使用“connected-react-router”。
import axios from "axios";
import { push } from "connected-react-router";
export myFunction = () => {
return async (dispatch) => {
try {
dispatch({ type: "GET_DATA_REQUEST" });
const { data } = await axios.get("URL");
dispatch({
type: "GET_DATA_SUCCESS",
payload: data
});
} catch (error) {
dispatch({
type: "GET_DATA_FAIL",
payload: error,
});
dispatch(push("/notfound"));
}
};
};
注意--请先到https://github.com/supasate/connected-react-router阅读文档并设置connected-react-router
,然后使用connected-react-router
中的“推送”。
答案 4 :(得分:1)
路由器4+版的最简单解决方案:
从初始化位置导出浏览器历史记录 并使用browserHistory.push('/ pathToRedirect'):
必须安装包装历史记录(例如:“ history”:“ 4.7.2”):
npm install --save history
在我的项目中,我在index.js中初始化浏览器历史记录:
import { createBrowserHistory } from 'history';
export const browserHistory = createBrowserHistory();
重定向操作:
export const actionName = () => (dispatch) => {
axios
.post('URL', {body})
.then(response => {
// Process success code
dispatch(
{
type: ACTION_TYPE_NAME,
payload: payload
}
);
}
})
.then(() => {
browserHistory.push('/pathToRedirect')
})
.catch(err => {
// Process error code
}
);
});
};
答案 5 :(得分:0)
You can use {withRouter} from 'react-router-dom'
Example below demonstrates a dispatch to push
export const registerUser = (userData, history) => {
return dispatch => {
axios
.post('/api/users/register', userData)
.then(response => history.push('/login'))
.catch(err => dispatch(getErrors(err.response.data)));
}
}
The history arguments is assigned to in the component as the a second parameter to the action creator (in this case 'registerUser')
答案 6 :(得分:0)
signup = e => {
e.preventDefault();
const { username, fullname, email, password } = e.target.elements,
{ dispatch, history } = this.props,
payload = {
username: username.value,
//...<payload> details here
};
dispatch(userSignup(payload, history));
// then in the actions use history.push('/<route>') after actions or promises resolved.
};
render() {
return (
<SignupForm onSubmit={this.signup} />
//... more <jsx/>
)
}
答案 7 :(得分:0)
这是路由应用的有效copy
import {history, config} from '../../utils'
import React, { Component } from 'react'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import Login from './components/Login/Login';
import Home from './components/Home/Home';
import reducers from './reducers'
import thunk from 'redux-thunk'
import {Router, Route} from 'react-router-dom'
import { history } from './utils';
const store = createStore(reducers, applyMiddleware(thunk))
export default class App extends Component {
constructor(props) {
super(props);
history.listen((location, action) => {
// clear alert on location change
//dispatch(alertActions.clear());
});
}
render() {
return (
<Provider store={store}>
<Router history={history}>
<div>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
</div>
</Router>
</Provider>
);
}
}
export const config = {
apiUrl: 'http://localhost:61439/api'
};
import { createBrowserHistory } from 'history';
export const history = createBrowserHistory();
//index.js
export * from './config';
export * from './history';
export * from './Base64';
export * from './authHeader';
import { SHOW_LOADER, AUTH_LOGIN, AUTH_FAIL, ERROR, AuthConstants } from './action_types'
import Base64 from "../utils/Base64";
import axios from 'axios';
import {history, config, authHeader} from '../utils'
import axiosWithSecurityTokens from '../utils/setAuthToken'
export function SingIn(username, password){
return async (dispatch) => {
if(username == "gmail"){
onSuccess({username:"Gmail"}, dispatch);
}else{
dispatch({type:SHOW_LOADER, payload:true})
let auth = {
headers: {
Authorization: 'Bearer ' + Base64.btoa(username + ":" + password)
}
}
const result = await axios.post(config.apiUrl + "/Auth/Authenticate", {}, auth);
localStorage.setItem('user', result.data)
onSuccess(result.data, dispatch);
}
}
}
export function GetUsers(){
return async (dispatch) => {
var access_token = localStorage.getItem('userToken');
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
var auth = {
headers: authHeader()
}
debugger
const result = await axios.get(config.apiUrl + "/Values", auth);
onSuccess(result, dispatch);
dispatch({type:AuthConstants.GETALL_REQUEST, payload:result.data})
}
}
const onSuccess = (data, dispatch) => {
const {username} = data;
//console.log(response);
if(username){
dispatch({type:AuthConstants.LOGIN_SUCCESS, payload: {Username:username }});
history.push('/');
// Actions.DashboardPage();
}else{
dispatch({ type: AUTH_FAIL, payload: "Kullanici bilgileri bulunamadi" });
}
dispatch({ type: SHOW_LOADER, payload: false });
}
const onError = (err, dispatch) => {
dispatch({ type: ERROR, payload: err.response.data });
dispatch({ type: SHOW_LOADER, payload: false });
}
export const SingInWithGmail = () => {
return { type :AuthConstants.LOGIN_SUCCESS}
}
export const SignOutGmail = () => {
return { type :AuthConstants.LOGOUT}
}
答案 8 :(得分:0)
使用挂钩的最新答案;路由器v5用户。
致力于
react-router-dom:5.1.2
。
不需要安装外部软件包。
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
您可以像以前一样使用history
。
更多详细信息和API-阅读manual