액션 리덕스 후 리액트라우터 리다이렉트
하고 react-redux ★★★★★★★★★★★★★★★★★」react-router액션이 디스패치된 후 리다이렉트해야 합니다.
예를 들어 다음과 같습니다.몇 가지 절차가 있습니다.작업 후:
function registerStep1Success(object) {
return {
type: REGISTER_STEP1_SUCCESS,
status: object.status
};
}
registration Step2의 페이지로 리다이렉트 하고 싶다.이거 어떻게 해?
p.s. 기록에서 브라우저 '/registrationStep2'를 방문하지 않았습니다.이 페이지는 결과 등록 Step1 페이지가 성공한 후에만 표시됩니다.
2액션을 마다 React Router 2+를 호출할 수 .browserHistory.push() (오류)hashHistory.push()다음 중 하나:
import { browserHistory } from 'react-router'
// ...
this.props.dispatch(registerStep1Success())
browserHistory.push('/registrationStep2')
비동기 작업 작성자에서도 사용할 수 있습니다.
리액트-라우터-리듀스 확인해봤어?이 라이브러리를 사용하면 리액트 라우터를 리덕스와 동기화할 수 있습니다.
다음으로 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'))
라우터 버전 4+의 가장 간단한 솔루션: "react-router-dom": "4.3.1" 버전 5+에서는 동작하지 않습니다.
브라우저 이력을 초기화된 위치에서 내보내고 browserHistory.push('/pathToRedirect')를 사용합니다.
패키지 이력을 인스톨 할 필요가 있습니다(예: 「이력」: 「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
}
);
});
};
답변을 에니 아린데의 하겠습니다.store.dispatchaction : 비동기 액션 후 :
export function myAction(data) {
return (dispatch) => {
dispatch({
type: ACTION_TYPE,
data,
}).then((response) => {
dispatch(push('/my_url'));
});
};
}
리듀서는 부작용이 없어야 하므로 리듀서가 아닌 액션 파일로 하는 것이 요령입니다.
"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.
'react-router-dom'에서 {withRouter}을(를) 사용할 수 있습니다.
다음 예시는 푸시할 디스패치를 보여줍니다.
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)));
}
}
history 인수는 작업 생성자에 대한 두 번째 매개 변수로 구성 요소에서 에 할당됩니다(이 경우 'registerUser').
후크를 사용한 갱신된 응답(라우터 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 - 매뉴얼을 참조하십시오.
라우팅 앱 작업 복사본입니다.
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}
}
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/>
)
}
react-router-dom 버전 +5를 사용하는 동안에는 redux(redux toolkit)에서 History 훅을 사용할 수 없습니다.
따라서 액션이 디스패치된 후 리다이렉트 할 경우 현재 페이지(컴포넌트)에서 "useHistory() 훅을 통해" 이력을 취득하여 payload와 함께 redex 인수로 전달할 수 있습니다.따라서 history.push("something")와 같이 액션이 디스패치된 후 이력을 redex로 쉽게 관리할 수 있습니다.
언급URL : https://stackoverflow.com/questions/35706835/react-router-redirect-after-action-redux
'programing' 카테고리의 다른 글
| 사용자 지정 게시 유형의 분류법 값을 가져오는 방법 (0) | 2023.03.21 |
|---|---|
| Gson - 자동 따옴표(")가 이스케이프됩니까? (0) | 2023.03.21 |
| 주식 시세 API? (0) | 2023.03.21 |
| SID가 Oracle tnsnames.ora의 서비스 이름과 어떻게 다른지 (0) | 2023.03.21 |
| 여러 쿼리를 사용하는 복잡한 Wordpress 쿼리 (0) | 2023.03.21 |