如何从angular6使用mapStateToProps?

时间:2018-06-30 03:20:23

标签: angular redux react-redux

我是React Lover,我在Angular Application中实现Redux,但是我在使用mapStateToProps获取存储数据时遇到问题,该怎么办?

  

它抛出一个错误store_1。connect不是一个函数

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { NgRedux, NgReduxModule, connect } from '@angular-redux/store';
import { IAppState, rootReducer, INITIAL_STATE } from './store';

import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    NgReduxModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { 
    constructor (ngRedux: NgRedux<IAppState>) {
            ngRedux.configureStore(rootReducer, INITIAL_STATE);

    }
}

const mapStateToProps = (state) =>  {
   console.log(state);
   return {
     state
   }
}

export default connect(mapStateToProps, null)(AppModule);

1 个答案:

答案 0 :(得分:1)

这里没有connect。使用Angular时,您通常会处理rxjs中的Observable。

@angular-redux/store库使用Select Pattern访问存储,因为它非常有效地插入了Angular的变更检测机制。

它为我们提供了两种选择:

@select装饰器

// this selects `counter` from the store and attaches it to this property
// it uses the property name to select, and ignores the $ from it
@select() counter$;

// this selects `counter` from the store and attaches it to this property
@select() counter;

// this selects `counter` from the store and attaches it to this property
@select('counter') counterSelectedWithString;

// this selects `pathDemo.foo.bar` from the store and attaches it to this
// property.
@select(['pathDemo', 'foo', 'bar']) pathSelection;

// this selects `counter` from the store and attaches it to this property
@select(state => state.counter) counterSelectedWithFunction;

// this selects `counter` from the store and multiples it by two
@select(state => state.counter * 2)
counterSelectedWithFuntionAndMultipliedByTwo: Observable<any>;

在构造函数中注入NgRedux实例(感谢Angular DI):

import * as CounterActions from '../actions/CounterActions';
import { NgRedux } from '@angular-redux/store';

@Component({
    selector: 'root',
    template: `
  <counter [counter]="counter$| async"
    [increment]="increment"
    [decrement]="decrement">
  </counter>
  `
})
export class Counter {
  private count$: Observable<number>;

  constructor(private ngRedux: NgRedux<IAppState>) {}

  ngOnInit() {
    let {increment, decrement } = CounterActions;
    this.counter$ = this.ngRedux.select('counter');
  }

  incrementIfOdd = () => this.ngRedux.dispatch(
    <any>CounterActions.incrementIfOdd());

  incrementAsync = () => this.ngRedux.dispatch(
    <any>CounterActions.incrementAsync());
}

对于RxJS繁重的Angular世界,您可以将这种模式视为reselect的高效模拟。

有关完整示例,请参见example-app simple counter example