programing

비동기 redux 액션 성공 시 다른 루트로 이행

instargram 2023. 3. 8. 20:35
반응형

비동기 redux 액션 성공 시 다른 루트로 이행

매우 간단한 반응 컴포넌트 세트가 있습니다.

  • container리덕스에 접속하여 액션을 처리하거나 구독을 저장하는 것 등
  • list내 아이템 목록이 표시됩니다.
  • new목록에 새 항목을 추가하기 위한 양식입니다.

다음과 같은 리액트라우터 루트가 있습니다.

<Route name='products' path='products' handler={ProductsContainer}>
  <Route name='productNew' path='new' handler={ProductNew} />
  <DefaultRoute handler={ProductsList} />
</Route>

그 때문에,list또는form표시되지만 둘 다 표시되지 않습니다.

새로운 아이템이 정상적으로 추가되면 어플리케이션이 목록으로 재루팅되도록 하고 싶습니다.

지금까지의 저의 해결책은.then()비동기 후에dispatch:

dispatch(actions.addProduct(product)
  .then(this.transitionTo('products'))
)

이것이 올바른 방법입니까?아니면 다른 액션을 실행하여 루트 변경을 트리거해야 합니까?

Redex Router와 같은 보다 완벽한 솔루션을 사용하지 않으려면 다음과 같은 코드를 작성할 수 있는 Redex History Transitions를 사용할 수 있습니다.

export function login() {
  return {
    type: LOGGED_IN,
    payload: {
      userId: 123
    }
    meta: {
      transition: (state, action) => ({
        path: `/logged-in/${action.payload.userId}`,
        query: {
          some: 'queryParam'
        },
        state: {
          some: 'state'
        }
      })
    }
  };
}

이것은 당신이 제안한 것과 비슷하지만 조금 더 정교합니다.후드 아래에서도 같은 이력 라이브러리를 사용하고 있기 때문에 리액트 라우터와 호환성이 있습니다.

결국 이렇게 생긴 매우 심플한 미들웨어를 만들었습니다.

import history from "../routes/history";

export default store => next => action => {

    if ( ! action.redirect ) return next(action);

    history.replaceState(null, action.redirect);
}

그러니까 거기서부터 네가 원하는 게 뭔지 확인해주면 돼successful액션에는redirect소유물.또한 이 미들웨어는 트리거되지 않습니다.next()루트 전환이 액션체인의 마지막이어야 하므로 이는 의도적으로 이루어집니다.

미들웨어 API 레이어를 사용하여 동형 fetch와 같은 사용법을 추상화하고 redux-thunk를 사용하고 있는 사용자에게는 단순히 체인을 분리할 수 있습니다.dispatch당신의 행동 속에서 다음과 같이 약속하세요.

import { push } from 'react-router-redux';
const USER_ID = // imported from JWT;

function fetchUser(primaryKey, opts) {
    // this prepares object for the API middleware
}

// this can be called from your container
export function updateUser(payload, redirectUrl) {
    var opts = {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    };
    return (dispatch) => {
        return dispatch(fetchUser(USER_ID, opts))
            .then((action) => {
                if (action.type === ActionTypes.USER_SUCCESS) {
                    dispatch(push(redirectUrl));
                }
            });
    };
}

이것에 의해, 여기서 제안하는 대로 코드에 라이브러리를 추가할 필요가 없어져, redux-history-transitions 로 동작과 리다이렉트를 적절히 조합할 수 있습니다.

저희 가게의 외관은 다음과 같습니다.

import { createStore, applyMiddleware } from 'redux';
import rootReducer from '../reducers';
import thunk from 'redux-thunk';
import api from '../middleware/api';
import { routerMiddleware } from 'react-router-redux';

export default function configureStore(initialState, browserHistory) {
    const store = createStore(
        rootReducer,
        initialState,
        applyMiddleware(thunk, api, routerMiddleware(browserHistory))
    );

    return store;
}

리액트 내비게이션은 이미 리액트 네이티브 매뉴얼에 포함되어 있기 때문에 파티에 늦었지만, Navigator api를 앱에서 사용/사용한 사용자에게도 도움이 될 수 있습니다.제가 시도했던 것은 조금 해킹적이었습니다.renderScene이 발생하자마자 오브젝트에 내비게이터 인스턴스를 저장하려고 합니다.

renderScene(route, navigator) {
      const Component = Routes[route.Name]
      api.updateNavigator(navigator); //will allow us to access navigator anywhere within the app
      return <Component route={route} navigator={navigator} data={route.data}/>

}

내 api 파일은 이것과 같은 것이다.

'use strict';

//this file includes all my global functions
import React, {Component} from 'react';
import {Linking, Alert, NetInfo, Platform} from 'react-native';
var api = {
    navigator,
    isAndroid(){
        return (Platform.OS === 'android');
    },
    updateNavigator(_navigator){
      if(_navigator)
          this.navigator = _navigator;
    },
}

module.exports = api;

이제 당신의 행동에서 당신은 간단히 호출할 수 있습니다.

api.navigator.push({이름:'routeName', 데이터:어떤 것이든…당신을 원했습니다.TO_PASS)

모듈에서 api를 Import하기만 하면 됩니다.

react-reduxreact-router를 사용하는 경우 이 링크는 훌륭한 솔루션을 제공합니다.

다음은 제가 사용한 단계입니다.

  • 라우터를 history 프로포트는 의 컴포넌트를 .<Route/> 고차 .withRouter.
  • 는 제 경로라고 ).to를 참조해 주세요.
  • 번째,을 리덕스 액션이라고 .history ★★★★★★★★★★★★★★★★★」to.
  • 리다이렉트 싶은 경우를 들어 해결되었을 때)에합니다.history.push(to).

언급URL : https://stackoverflow.com/questions/32612418/transition-to-another-route-on-successful-async-redux-action

반응형