Reactjs 操作后反应路由器重定向redux
我正在使用Reactjs 操作后反应路由器重定向redux,reactjs,react-router,redux,redux-framework,Reactjs,React Router,Redux,Redux Framework,我正在使用react-redux和react-router。我需要在发送操作后重定向 例如:我有几个步骤。行动后: function registerStep1Success(object) { return { type: REGISTER_STEP1_SUCCESS, status: object.status }; } 我想重定向到注册步骤2的页面。我该怎么做 p、 未访问历史记录浏览器“/registrationStep2”中的美国。此页面
react-redux
和react-router
。我需要在发送操作后重定向
例如:我有几个步骤。行动后:
function registerStep1Success(object) {
return {
type: REGISTER_STEP1_SUCCESS,
status: object.status
};
}
我想重定向到注册步骤2的页面。我该怎么做
p、 未访问历史记录浏览器“/registrationStep2”中的美国。此页面仅在成功注册结果步骤1页面后显示。您签出了吗?此库使react路由器与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'))
使用React Router 2+,无论您在何处调度操作,都可以调用
browserHistory.push()
(或者hashHistory.push()
,如果您使用的是该操作):
如果您使用的是异步操作创建者,您也可以使用它。要在Eni Arinde之前的答案(我没有评论的声誉)的基础上进行构建,以下是如何在异步操作后使用
store.dispatch
方法:
export function myAction(data) {
return (dispatch) => {
dispatch({
type: ACTION_TYPE,
data,
}).then((response) => {
dispatch(push('/my_url'));
});
};
}
诀窍是在操作文件中而不是在还原程序中执行,因为还原程序不应该有副作用。您可以使用“react router dom”中的{}
下面的示例演示了一个要推送的分派
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)));
}
}
历史参数在组件中作为第二个参数分配给操作创建者(在本例中为“registerUser”)signup=e=>{
e、 预防默认值();
const{username,fullname,email,password}=e.target.elements,
{dispatch,history}=this.props,
有效载荷={
用户名:username.value,
//…这里有详细信息
};
调度(用户注册(有效载荷、历史记录));
//然后在操作中,在解决操作或承诺后使用history.push(“/”)。
};
render(){
返回(
//……更多
)
}
路由器版本4+的最简单解决方案:
我们使用“react router dom”:“4.3.1”
它不适用于版本5+
从初始化位置导出浏览器历史记录
并使用browserHistory.push('/pathToRedirect'):
必须安装程序包历史记录(例如:“历史记录”:“4.7.2”):
在我的项目中,我在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
}
);
});
};
以下是路由应用程序的工作原理
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}
}
从'../../utils'导入{history,config}
从“React”导入React,{Component}
从“react redux”导入{Provider}
从“redux”导入{createStore,applyMiddleware}
从“./components/Login/Login”导入登录名;
从“./components/Home/Home”导入Home;
从“./还原程序”导入还原程序
从“redux thunk”导入thunk
从“react Router dom”导入{Router,Route}
从“/utils”导入{history};
const store=createStore(还原器、applyMiddleware(thunk))
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具);
历史。聆听((位置、动作)=>{
//位置更改时清除警报
//分派(alertActions.clear());
});
}
render(){
返回(
);
}
}
导出常量配置={
apiUrl:'http://localhost:61439/api'
};
从“历史”导入{createBrowserHistory};
export const history=createBrowserHistory();
//index.js
从“/config”导出*;
导出*自“./历史记录”;
从“/Base64”导出*;
从“/authHeader”导出*;
从“/action\u types”导入{SHOW\u LOADER、AUTH\u LOGIN、AUTH\u FAIL、ERROR、AuthConstants}
从“./utils/Base64”导入Base64;
从“axios”导入axios;
从“../utils”导入{history,config,authHeader}
从“../utils/setAuthToken”导入axiosWithSecurityTokens
导出函数SingIn(用户名、密码){
返回异步(调度)=>{
如果(用户名==“gmail”){
onSuccess({username:“Gmail”},dispatch);
}否则{
分派({type:SHOW_LOADER,payload:true})
让auth={
标题:{
授权:“承载人”+Base64.btoa(用户名+:“+密码)
}
}
const result=await axios.post(config.apirl+“/Auth/Authenticate”,{},Auth);
localStorage.setItem('user',result.data)
onSuccess(结果、数据、调度);
}
}
}
导出函数GetUsers(){
返回异步(调度)=>{
var access_token=localStorage.getItem('userToken');
axios.defaults.headers.common['Authorization']=`Bearer${access\u token}`
var auth={
标题:authHeader()
}
调试器
const result=await axios.get(config.apirl+“/Values”,auth);
成功(结果、调度);
分派({type:AuthConstants.GETALL_请求,负载:result.data})
}
}
const onSuccess=(数据,调度)=>{
const{username}=数据;
//控制台日志(响应);
如果(用户名){
分派({type:AuthConstants.LOGIN_SUCCESS,负载:{Username:Username}});
历史推送(“/”);
//Actions.DashboardPage();
}否则{
调度({type:AUTH_FAIL,payload:“Kullanici bilgileri bulumanadi”});
}
分派({type:SHOW_LOADER,payload:false});
}
const onError=(错误,调度)=>{
分派({type:ERROR,payload:err.response.data});
分派({type:SHOW_LOADER,payload:false});
}
导出const SingInWithGmail=()=>{
返回{type:AuthConstants.LOGIN\u SUCCESS}
}
导出常量SignOutGmail=()=>{
返回{type:AuthConstants.LOGOUT}
}
使用钩子更新答案;适用于路由器v5用户
处理react路由器dom:5.1.2
无需安装外部包装
从“react router dom”导入{useHistory};
函数HomeButton(){
让历史=使用历史();
函数handleClick(){
历史·普
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
}
);
});
};
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}
}
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>
);
}