私はこのように定義されたコンポーネントを持っています。 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はブラウザレベルで失敗しますか?
を必要としますが、これは別のアクションをディスパッチするハンドル(store.dispatch({何}))と反応することができます。 – Gregg