2016-08-29 12 views
1

私はこのように定義されたコンポーネントを持っています。 fetchBrandsは還元作用である。reduxアクションからの未保証のAjaxリクエストの防止

class Brands extends Component { 

    componentWillMount() { 
    this.props.fetchBrands(); 
    } 

    render() { 
    return (
     // jsx omitted for brevity 
    ); 
    } 
} 

function mapStateToProps(state) { 
    return { brands: state.brands.brands } 
} 

export default connect(mapStateToProps, { fetchBrands: fetchBrands })(Brands); 

このコンポーネントは、次のようになり高次コンポーネントに包まれて:

<Route path="brands" component={requireAuth(Brands)} />

:私のルータの設定で、

export default function(ComposedComponent) { 
    class Authentication extends Component { 

    // kind if like dependency injection 
    static contextTypes = { 
     router: React.PropTypes.object 
    } 

    componentWillMount() { 
     if (!this.props.authenticated) { 
     this.context.router.push('/'); 
     } 
    } 

    componentWillUpdate(nextProps) { 
     if (!nextProps.authenticated) { 
     this.context.router.push('/'); 
     } 
    } 

    render() { 
     return <ComposedComponent {...this.props} /> 
    } 
    } 

    function mapStateToProps(state) { 
    return { authenticated: state.auth.authenticated }; 
    } 

    return connect(mapStateToProps)(Authentication); 
} 

その後、私は次のことをやっていますauthトークンがローカルストレージに存在しない場合、私はパブリックページにリダイレクトします。しかし、fetchBrandsアクションはまだ呼び出されており、これはajaxリクエストを起動しています。サーバーは認証トークンがないためにサーバーを拒否していますが、その呼び出しを行うことは望ましくありません。

export function fetchBrands() { 
    return function(dispatch) { 
    // ajax request here 
    } 
} 

どのようにしている場合の呼び出しを防ぐために、DRY何かを実装することができます。私はif/elseチェックでAJAXリクエストを包むことができますが、それは私がこれを行うために必要があると思い、すべてのアクション関数を考慮非常に乾燥していませんauthはブラウザレベルで失敗しますか?

答えて

0

ミドルウェアを記述する必要があります。 http://redux.js.org/docs/advanced/Middleware.html

あなたは、私が本当に

const tokenMiddleware = store => next => action => { 
    if (action.payload && action.payload.request && action.payload.request.secure) { 
    const { auth: { isAuthenticated } } = store.getState() 
    const secure = action.payload.request.secure 

    if (!isAuthenticated && secure) { 
     history.push({ pathname: 'login', query: { next: history.getCurrentLocation().pathname } }) 
     return Promise.reject(next({ type: 'LOGIN_ERROR', ...omit(action, 'payload') })) 
    } 
    } 

    return next(action) 
} 

action.payload.request.secureは、私が使用するカスタム小道具であるように、あなたがミドルウェアを使用することができますhttps://github.com/svrcekmichal/redux-axios-middleware

ようなものを使用することをお勧めしますaxiosを使用しているのでリクエストに認証が必要であることを示します。

Iこの場合、私も反応し、ルータからの歴史を使用してリダイレクトいますがaxiosと約束ミドルウェアを使用して

+0

を必要としますが、これは別のアクションをディスパッチするハンドル(store.dispatch({何}))と反応することができます。 – Gregg

関連する問題